如何将BitmapImage转换为字节数组

时间:2014-03-13 07:40:50

标签: windows-phone-8 winrt-xaml

我需要做以下事情:

  1. 将base64图像字符串转换为Bitmapimage
  2. 来自(1)中的BitmapImage,将其转换为byteArray
  3. 问题: 如何解决步骤(2)

    非常感谢您的帮助。感谢

    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 个答案:

答案 0 :(得分:1)

检查此方法

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;
}