Convert Bitmap Image to byte array (Windows phone 8)

匆匆过客 提交于 2019-12-20 05:37:06

问题


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:

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

But then I saved this byte array to image in photogallery, I was be a black image!

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

Could anyone help me? Please test your code :( Thanks so much!


Update resolved!

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

回答1:


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



回答2:


for windows phone 8

using 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")


来源:https://stackoverflow.com/questions/22241480/convert-bitmap-image-to-byte-array-windows-phone-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!