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();

     }


}

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is Extensions.SaveJpeg() supported in WinRT? If so, How to import it? I tried in WinRT, it seems not suported.
Oh I was not confirmed with the development target.. just check this link stackoverflow.com/questions/12963508/…
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.