Creating a Byte array from an Image

天大地大妈咪最大 提交于 2019-12-12 04:43:54

问题


What is the best way to create a byte array from an Image? I have seen many methods but in WinRT none of them worked.


回答1:


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:


here is one way http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap.aspx

alternatively if you have the Image saved on FS, just create a StorageFile and use the stream to get byte[]




回答3:


The magic is in the DataReader class. For example ...

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



回答4:


I have used the method 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();

        }


来源:https://stackoverflow.com/questions/15005212/creating-a-byte-array-from-an-image

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