Im trying to insert into my table some image from picturebox:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
command.CommandText = "INSERT INTO ImagesTable (Image) VALUES('" + photo + "')";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
I get the following result in database:
ID Image
6 0x53797374656D2E427974655B5D
However when I insert some image using SQL script:
insert into ImagesTable (Image)
SELECT BulkColumn
FROM Openrowset( Bulk 'C:\pinguins.jpg', Single_Blob) as img
Then inserted data looks like this:
ID Image
4 0xFFD8FFE000104A464946000102010[.....]
Here binary data is much much longer.
When I retrieve this image from database back into picturebox, it shows up correctly:
command.CommandText = "SELECT Image FROM ImagesTable where ID = 4";
byte[] image = (byte[])command.ExecuteScalar();
MemoryStream ms1 = new MemoryStream(image);
pictureBox2.Image = Bitmap.FromStream(ms1);
But I get error when retrieving image with ID = 6 (loaded from pictureBox).
ArgumentException: Parameter is not valid.
What am I doing wrong?
I'd appreciate any advice.
write this way:]
Image img = Image.FromFile(@"C:\Lenna.jpg");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
arr = ms.ToArray();
}
or
Image img = picturebox1.Image();
byte[] arr;
ImageConverter converter = new ImageConverter();
arr=(byte[])converter.ConvertTo(img, typeof(byte[]));
command.CommandText = "INSERT INTO ImagesTable (Image) VALUES('" + arr + "')";
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With