2

My friends, I am trying convert a image to a Base64 String in a c# console app (.net 4.0).

The method:

public static String ConvertBitmapToBase64String(Bitmap bitmap, 
                                                 ImageFormat imageFormat)
{
    String generatedString = string.Empty;

    MemoryStream memoryStream = new MemoryStream();
    bitmap.Save(memoryStream, imageFormat);

    memoryStream.Position = 0;
    byte[] byteBuffer = memoryStream.ToArray();

    memoryStream.Close();

    generatedString = Convert.ToBase64String(byteBuffer);

    byteBuffer = null;

    return generatedString;
}

But when I invoke this method it is throwing an exception saying: "generic gdi+ error" and the error number is -2147467259.

Invoker code:

StreamReader streamReader = new StreamReader(@"C:\Anita.jpg");
Bitmap bitmap = new Bitmap(streamReader.BaseStream);

streamReader.Close();

String base64String = ImageUtil.ConvertBitmapToBase64String(bitmap, ImageFormat.Jpeg);

Anybody can give me a help? Thanks.

Jean J. Michel
  • 561
  • 1
  • 7
  • 14
  • Duplicate - check this post: http://stackoverflow.com/questions/1053052/a-generic-error-occurred-in-gdi-jpeg-image-to-memorystream – maseal Sep 25 '13 at 17:30

1 Answers1

0

The only likely problem I see is that the image is too large or big. Perhaps, instead of using a MemoryStream, you can use File.ReadAllBytes directly instead of passing around the Bitmap object, saving directly to a MemoryStream, and saving.

Also, you're reading the data in with a StreamReader, which is meant for text! Moving to just reading the bytes into an array and calling Convert.ToBase64String() should handle what you want to do.

Adam Sears
  • 355
  • 4
  • 14