将位图图像转换为字节数组(Windows Phone 8)

时间:2014-03-07 04:30:48

标签: bytearray

我是windows phone dev的新手。我的小应用程序需要图像(照片库)中的bytesarray。我尝试了许多转换方法,但它没有正常工作。

这是我的代码:

public static byte[] ConvertBitmapImageToByteArray(BitmapImage bitmapImage)
    {
        using (var ms = new MemoryStream())
        {
            var btmMap = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
            // write an image into the stream
            btmMap.SaveJpeg(ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
            return ms.ToArray();
        }
    }

但后来我把这个字节数组保存到了照片库中的图像中,我是一个黑色图像!

public static void SavePicture2Library(byte[] bytes)
    {
        var library = new MediaLibrary();
        var name = "image_special";
        library.SavePicture(name, bytes);
    }

有人能帮帮我吗? 请测试你的代码:(非常感谢!


更新已解决!

var wBitmap = new WriteableBitmap(bitmapImage);
            wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
            stream.Seek(0, SeekOrigin.Begin);
            data = stream.GetBuffer();

2 个答案:

答案 0 :(得分:3)

对于任何发现这一点的人来说,这都有效;

图像到字节;

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

字节到图像

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

答案 1 :(得分:0)

用于Windows Phone 8

使用System.IO;

public static class FileToByteArray
{
    public static byte[] Convert(string pngBmpFileName)
    {
        System.IO.FileStream fileStream = File.OpenRead(pngBmpFileName);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            fileStream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }
}
byte[] PasPhoto = FileToByteArray.Convert("Images/NicePhoto.png")