2

Possibly Answered Here: storing image to byte[] into Mysql using asp.net and c#

using System.Drawing;
using System.Drawing.Imaging;

var imageBytes = imageToByteArray(pictureBox1.Image);     

var insert = new MySqlCommand("Insert INTO itemimage set imageName = '" + imageBytes + "'", _con);

insert.ExecuteNonQuery();   


public byte[] imageToByteArray(Image imageIn)
{
    var ms = new MemoryStream();
    imageIn.Save(ms, ImageFormat.Gif);
    return ms.ToArray();
}

Table: itemimage
2 | System.Byte[]  | 13byte    

3 | System.Byte[]  | 13byte

What is wrong with this code? thanks.

1 Answer 1

5

What is wrong with this code?

You're using string concatenation to form the SQL. That's calling ToString on a byte array, which gives System.Byte[] as the result.

Instead, use a parameterized query, and set the parameter value to your byte array.

Something like this:

var data = ImageToByteArray(pictureBox.Image);
using (var cmd = new MySqlCommand("INSERT INTO itemimage SET imageName = @image",
                                  _con))
{
    cmd.Parameters.Add("@image", MySqlDbType.Blob).Value = data;
    cmd.ExecuteNonQuery();
}

Mind you, I'm a bit concerned about the column name here - is it really meant to be the name of an image (which is what the column name suggests) or the data in an image (which is what your code suggests)? Those are two very different things, and you should make it clear which is which.

You should always use parameterized queries:

  • They prevent SQL injection attacks
  • They reduce data conversion issues
  • They separate the code from the data more cleanly
Sign up to request clarification or add additional context in comments.

3 Comments

Can you do an example code sir Jon, sorry noob here. Thanks for your consideration.
right now I got: (Binary/Image). Once again, thank you for being generous with your example. Now I can understand more. I hope this could also help other people like me. Good Day.!
Yeah for sure. Got the same issue. Same solution worked. Upvoted. Thanks for this a lot! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.