从图像创建字节数组

时间:2013-02-21 14:50:15

标签: windows-8 windows-runtime winrt-xaml

从Image创建字节数组的最佳方法是什么?我见过很多方法,但在WinRT中,没有一种方法有效。

4 个答案:

答案 0 :(得分:2)

这是一种方式 http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx

或者如果您在FS上保存了图像,只需创建一个StorageFile并使用该流来获取byte []

答案 1 :(得分:2)

static class ByteArrayConverter
    {
        public static async Task<byte[]> ToByteArrayAsync(StorageFile file)
        {
            using (IRandomAccessStream stream = await file.OpenReadAsync())
            {
                using (DataReader reader = new DataReader(stream.GetInputStreamAt(0)))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    byte[] Bytes = new byte[stream.Size];
                    reader.ReadBytes(Bytes);
                    return Bytes;
                }
            }
        }
    }

答案 2 :(得分:1)

魔法在DataReader class。例如......

var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.png"));
var buf = await FileIO.ReadBufferAsync(file);
var bytes = new byte[buf.Length];
var dr = DataReader.FromBuffer(buf);
dr.ReadBytes(bytes);

答案 3 :(得分:0)

我使用了方法from Charles Petzold

        byte[] srcPixels;
        Uri uri = new Uri("http://www.skrenta.com/images/stackoverflow.jpg");
        RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);

        using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(fileStream);
            BitmapFrame frame = await decoder.GetFrameAsync(0);

            PixelDataProvider pixelProvider = await frame.GetPixelDataAsync();
            srcPixels = pixelProvider.DetachPixelData();

        }