1

i am trying to convert a bitmap to a base64 string.i can convert to from string to bitmap...but it seems like there is a problem when converting from bitmap to string.I was hoping you guys could give me a hand

    public static string BitmapToString(BitmapImage image)
    {

        Stream stream = image.StreamSource ;
        Byte[] buffer = null;
        if (stream != null && stream.Length > 0)
        {
            using (BinaryReader br = new BinaryReader(stream))
            {
                buffer = br.ReadBytes((Int32)stream.Length);
            }
        }

        return Convert.ToBase64String(buffer);
    }

it gets a ArgumentNullException was unhandled Value cannot be null. Parameter name: inArray when returning Convert.ToBase64String(buffer)

Help?

H.B.
  • 166,899
  • 29
  • 327
  • 400
ALex Popa
  • 339
  • 7
  • 16
  • Are you sure you enter the `if`? I think the problem is that the image has been loaded from an url and so there isn't any stream. – xanatos Mar 15 '12 at 19:25
  • doesnt enter the if..the thing is it says that the image.StreamSource is null..but it does get the right image – ALex Popa Mar 15 '12 at 19:28
  • Try this: http://stackoverflow.com/questions/553611/wpf-image-to-byte (the accepted solution) – xanatos Mar 15 '12 at 19:30

2 Answers2

3

Try this alternative:

 public string BitmapToBase64(BitmapImage bi)
        {
            MemoryStream ms = new MemoryStream();
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bi));
            encoder.Save(ms);
            byte[] bitmapdata = ms.ToArray();

            return Convert.ToBase64String(bitmapdata);
        }

In your solution, it is not necessary that StreamSource will always have value if it is loaded using a Uri.

Code0987
  • 2,598
  • 3
  • 33
  • 51
1

First of all, it is necessary to save BitmapImage data into memory using some bitmap encoder (PngBitmapEncoder for example).

public static byte[] EncodeImage(BitmapImage bitmapImage)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        BitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
        encoder.Save(memoryStream);
        return memoryStream.ToArray();
    }
}

Then just encode the binary data with Base64-encoding.

const string filePath = @"...";
const string outFilePath = @"...";
const string outBase64FilePath = @"...";

// Constuct test BitmapImage instance.
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = File.OpenRead(filePath);
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();

// Convert BitmapImage to byte array.
byte[] imageData = EncodeImage(bitmapImage);
File.WriteAllBytes(outFilePath, imageData);

// Encode with Base64.
string base64String = Convert.ToBase64String(imageData);

// Write to file (for example).
File.WriteAllText(outBase64FilePath, base64String);