Kristian Vukusic
Kristian Vukusic

Reputation: 3324

Creating a Byte array from an Image

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.

Upvotes: 0

Views: 1510

Answers (4)

Manic
Manic

Reputation: 223

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

Upvotes: 2

Kristian Vukusic
Kristian Vukusic

Reputation: 3324

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

        }

Upvotes: 0

JP Alioto
JP Alioto

Reputation: 45117

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

Upvotes: 1

Hermit Dave
Hermit Dave

Reputation: 3046

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

Upvotes: 2

Related Questions