Sumit Bhattarai
Sumit Bhattarai

Reputation: 308

Error converting image to byte for saving in database

I have a win form with picture box and i want to store image to database so while converting image to byte to store in database I am getting the error.How to solve the error? Here is my code and I have also pointed out the line at which error (object reference not set to instance of object) occurs:

   public string ImageToBase64(Image image,
      System.Drawing.Imaging.ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);-------Error at this point----
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }

Upvotes: 1

Views: 130

Answers (1)

Pushpendra
Pushpendra

Reputation: 1712

Instead of

   using (MemoryStream ms = new MemoryStream())
    {
        // Convert Image to byte[]
        image.Save(ms, format);-------Error at this point----
        byte[] imageBytes = ms.ToArray();
          ..
     }

It should be:

    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        byte[] imageBytes = ms.ToArray();

    }

RawFormat property of image returns the format of image

EDIT 1

You could also try to use ImageConverter class

 ImageConverter converter = new ImageConverter();
 byte[] imageBytes= (byte[])converter.ConvertTo(img, typeof(byte[]));

EDIT 2

If you are saving bytearray in your database table then the columntype should be VARBINARY Else if you are saving base64string it should be VARCHAR(MAX) or VARCHAR(X)

Upvotes: 1

Related Questions