user3531533
user3531533

Reputation: 65

How to upload images to mysql database using C#?

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.

Upvotes: 3

Views: 4752

Answers (1)

csharpwinphonexaml
csharpwinphonexaml

Reputation: 3683

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);

Upvotes: 1

Related Questions