Convert Bitmap Image to byte array (Windows phone 8)

后端 未结 2 1603
轻奢々
轻奢々 2021-01-25 20:54

I am new to windows phone dev. My small app need a bytesarray from image (photo gallery). I tried many ways to convert, but it did not work fine.

here is my code:

<
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-25 20:58

    To anyone who finds this, this works;

    Image to bytes;

    public static byte[] ImageToBytes(BitmapImage img)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    WriteableBitmap btmMap = new WriteableBitmap(img);
                    System.Windows.Media.Imaging.Extensions.SaveJpeg(btmMap, ms, img.PixelWidth, img.PixelHeight, 0, 100);
                    img = null;
                    return ms.ToArray();
                }
            }
    

    Bytes to Image

    public static BitmapImage BytesToImage(byte[] bytes)
            {
                BitmapImage bitmapImage = new BitmapImage();
                try
                {
                    using (MemoryStream ms = new MemoryStream(bytes))
                    {
                        bitmapImage.SetSource(ms);
                        return bitmapImage;
                    }
                }
                finally { bitmapImage = null; }
            }
    

提交回复
热议问题