1

I need to do the following:

  1. Convert base64 image string into Bitmapimage
  2. from BitmapImage in (1), convert it to byteArray

The problem: how to solve the step(2)

Your help is greatly appreciated. Thanks

public async Task Base64StringToBitmap(string Base64source,string Filenm)
{
    var bytes = Convert.FromBase64String(Base64source);
    var ims = new InMemoryRandomAccessStream(); 
    var dataWriter = new DataWriter(ims);   
    dataWriter.WriteBytes(bytes); 
    await dataWriter.StoreAsync();  
    ims.Seek(0);

    //----- Create Bitmapimage ---------------

     var bm = new BitmapImage();
     bm.CreateOptions = BitmapCreateOptions.None;
     bm.SetSource(ims);

   // Update : added this   

     byte[] pixelBuffer = null;    

    using (MemoryStream ms = new MemoryStream())
    {

       WriteableBitmap wb = new WriteableBitmap(200, 300);
       wb.SetSource(ims);

      //-- Problem here :

       Stream stm = wb.PixelBuffer.AsStream();

       int len = (int)stm.Length;

       byte[] pixels = new byte[len];


       await stm.ReadAsync(pixels, 0, pixels.Length);               

        stm.CopyTo(ms);        

        pixelBuffer = ms.ToArray();

     }


}
MilkBottle
  • 4,242
  • 13
  • 64
  • 146

1 Answers1

1

Check this method

public static byte[] ConvertToBytes(BitmapImage bitmapImage)
{
    byte[] data = null;
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap
            (bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        // write an image into the stream
        Extensions.SaveJpeg(btmMap, ms,
            bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

        ms .Seek(0, SeekOrigin.Begin);
        data = stream.GetBuffer();
    }
    return data;
}
A.K.
  • 3,321
  • 1
  • 15
  • 27
  • Is Extensions.SaveJpeg() supported in WinRT? If so, How to import it? I tried in WinRT, it seems not suported. – MilkBottle Mar 13 '14 at 08:00
  • Oh I was not confirmed with the development target.. just check this link http://stackoverflow.com/questions/12963508/bitmapimage-to-byte-windows-8-metro-winrt – A.K. Mar 13 '14 at 08:02
  • Your method should work in Windows phone but not for WinRT. I have added some code. There is no error but the problem is it is reading forever and not stopping. any problem in my code? – MilkBottle Mar 13 '14 at 09:32