Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

c# - Insert PictureBox Image into Sql Server database

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...