bharathi
bharathi

Reputation: 6271

store the picturebox image to a database

I have a Picture box. The image in the picture box is a static one. I am loading the image from the resources folder. I am not able to read the static image from the picture box and store it in the database. here is my code.

 private void btnOk_Click(object sender, EventArgs e)
    {
        Image votingBackgroundImage = pictureBox5.Image;
        Bitmap votingBackgroundBitmap = new Bitmap(votingBackgroundImage);
         Image votingImage = (Image)votingBackgroundBitmap;
            var maxheight = (votingImage.Height * 3) + 2;
            var maxwidth = votingImage.Width * 2;
            if (maxheight == 227 && maxwidth == 720)
            {

                 System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream();
                 Bitmap NewImage =new Bitmap(votingImage,new Size(720,227));
                 Image b = (Image)NewImage;
                  b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
                 defaultImageData = new byte[defaultImageStream.Length];
              }
    }

Query I used to add the image in the database:

            String MyString1=string.format("insert into question_table(background_image) Values(@background_image)");
            com = new SqlCommand(MyString1, myConnection);
              com.Parameters.Add("@background_image", SqlDbType.Image).Value = defaultImageData;
                com.ExecuteNonQuery();

When I check this in the sql database.It stores the value as 0 x000000...

Upvotes: 2

Views: 6526

Answers (3)

Zenwalker
Zenwalker

Reputation: 1919

You have to store it as a Blob i.e byte array.

Upvotes: 0

Haris Hasan
Haris Hasan

Reputation: 30097

You are just creating the byte[] but you never actually copied the content

try

 System.IO.MemoryStream defaultImageStream = new System.IO.MemoryStream();
 Bitmap NewImage =new Bitmap(votingImage,new Size(720,227));
 Image b = (Image)NewImage;
 b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
 defaultImageData = new byte[defaultImageStream.Length];
 //assign byte array the content of image
 defaultImageData = defaultImageStream .ToArray();

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262939

It looks like you're allocating an array of bytes to store your stream's content, but you don't copy the content itself.

Maybe you don't need an intermediate array. Try using the ToArray() method of MemoryStream:

b.Save(defaultImageStream, System.Drawing.Imaging.ImageFormat.Bmp);
// ...
com.Parameters.Add("@background_image", SqlDbType.Image).Value
    = defaultImageStream.ToArray();

Upvotes: 0

Related Questions