0

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

4 Answers 4

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;
                }
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

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[]

Comments

1

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

2 Comments

i guess he meant reading the pixel data, not the file contents
thought the same thing... BUT in order to get the pixel data you have to reload the Image (capital "I") into a WriteableBitmap, and if you're doing that why not just read the source directly as @JP mentioned!
0

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

        }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.