0

I receive the below error when trying to save an image which is converted from a byte array and not too sure why. Unfortunately, the error doesn't provide much detail on what the actual problem is. Error and code below

Error:

Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

and code:

byte[] imageBytes = Convert.FromBase64String(base64string);
Image image;
MemoryStream ms = new MemoryStream(imageBytes);
image = Image.FromStream(ms);
image.Save("testImage.png", System.Drawing.Imaging.ImageFormat.Png);

EDIT: this error is thrown on the image.Save line

djv
  • 15,168
  • 7
  • 48
  • 72
GregH
  • 5,125
  • 8
  • 55
  • 109

1 Answers1

1

I created a small test method like your code that looks like the below:

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
    string base64String = Convert.ToBase64String(ms.ToArray());

    //Your code
    byte[] imageBytes = Convert.FromBase64String(base64String);
    System.IO.MemoryStream ms2 = new System.IO.MemoryStream(imageBytes);
    image = Image.FromStream(ms2);
    image.Save("testImage.tif", System.Drawing.Imaging.ImageFormat.Tiff);
}

The only difference from my code to yours is that it uses a .tif image as input to get the base64String.

When I have tested this it works fine with no error, therefore I suggest you check a few things:

  • The application has Read and Write permissions to the current directory
  • The testImage.png is not locked by another process
  • The base64String is valid and not providing errors
  • The image when loaded looks fine, i.e. display it in a PictureBox if your application runs in WindowsForms
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69