3

I am trying to insert an image from windows application to mysql database . while trying to do so i have encountered the following error

"Unable to cast object of type 'System.Byte[]' to type'System.IConvertible'."

public void LoadImages()          
{        
    MySqlConnection cn = new MySqlConnection(connstring);        
    cn.Open();    
    string image = txtLogo.Text;    
    byte[] ImageData;    
    FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);    
    BinaryReader br = new BinaryReader(fs);    
    ImageData = br.ReadBytes((int)fs.Length);    
    br.Close();    
    fs.Close();    
    MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(@Images,'"+txtEmailId.Text+"')", cn);    
    cmd.Parameters.AddWithValue("@Images", MySqlDbType.LongBlob).Value = ImageData;    
    cmd.ExecuteNonQuery();    
    cn.Close();    
}

Please help in clearing this error.

2
  • At witch line the error happens? Commented Apr 25, 2014 at 8:10
  • When i debugged the code error is shown at executenonquerry(; Commented Apr 25, 2014 at 8:52

1 Answer 1

1

This should do:

MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(?Images,'" + txtEmailIdText + "')", cn);

MySqlParameter parImage = new MySqlParameter();
parImage.ParameterName = "?Images";
parImage.MySqlDbType = MySqlDbType.MediumBlob;
parImage.Size = 3000000;
parImage.Value = ImageData;//here you should put your byte []

cmd.Parameters.Add(parImage);
cmd.ExecuteNonQuery();

This could be one way to check if the Image has been stored to db

//write your code to get the record from db to byte[] ImageData;
public Image byteArrayToImage(byte[] byteBLOBData )
{
    MemoryStream ms = new MemoryStream(byteBLOBData );
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}

call like this

PictureBox picture = new PictureBox();
picture.Image = byteArrayToImage(ImageData);
Controls.Add(picture);
Sign up to request clarification or add additional context in comments.

14 Comments

When you get it out you must process the bytes and show them as image
Depends what kind of application you are doing WPF WinForm ASP.NET?
ASP.NET (C#) its windows application
This should help you decide how to proceed on showing the Image stackoverflow.com/questions/18177351/…. As about the Writing the image to the database I think you have the answer
@user3531533 How do you know that it isn't?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.