0

I write the code below to convert image to byte array and convert back later, but it doesn't work. Anyone can help?

FileOpenPicker picker = new FileOpenPicker();
        picker.ViewMode = PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".png");
        StorageFile file = await picker.PickSingleFileAsync();
        byte[] pixeByte;
        using (IRandomAccessStream stream = await file.OpenReadAsync())
        {
            WriteableBitmap image = new WriteableBitmap(400, 250);
            image.SetSource(stream);
            testImage.Source = image;
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
            BitmapTransform transform = new BitmapTransform();
            transform.ScaledWidth = 400;
            transform.ScaledHeight = 250;
            PixelDataProvider pixeldata =await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
            pixeByte = pixeldata.DetachPixelData();
        }

        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            BitmapImage image = new BitmapImage();
            await stream.WriteAsync(pixeByte.AsBuffer());
            stream.FlushAsync().AsTask().Wait();
            stream.Seek(0);
             image.SetSource(stream);
            testImage2.Source = image;
        }

Solved:

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

    // Convert a byte array to BitmapImage
    public static async Task<BitmapImage> ByteArrayToImageAsync(byte[] pixeByte)
    {
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            BitmapImage image = new BitmapImage();
            await stream.WriteAsync(pixeByte.AsBuffer());
            stream.Seek(0);
            image.SetSource(stream);
            return image;
        }
    }
3
  • What do you mean by "It doesn't work"? Commented Dec 24, 2012 at 7:44
  • testImage2 doesn't display the image Commented Dec 24, 2012 at 9:34
  • Check this answer stackoverflow.com/a/13778983/772608 Commented Mar 24, 2013 at 7:34

1 Answer 1

2

I have pulled out the parts I used to convert a stream to a byte array:-

public async Task<byte[]> ImageToBytes(IRandomAccessStream sourceStream)
{
    byte[] imageArray;

    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(sourceStream);

    var transform = new BitmapTransform { ScaledWidth = decoder.PixelWidth, ScaledHeight = decoder.PixelHeight};
    PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
        BitmapPixelFormat.Rgba8,
        BitmapAlphaMode.Straight,
        transform,
        ExifOrientationMode.RespectExifOrientation,
        ColorManagementMode.DoNotColorManage);

    using (var destinationStream = new InMemoryRandomAccessStream())
    {
        BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, destinationStream);
        encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, decoder.PixelWidth,
                                decoder.PixelHeight, 96, 96, pixelData.DetachPixelData());
        await encoder.FlushAsync();

        BitmapDecoder outputDecoder = await BitmapDecoder.CreateAsync(destinationStream);
        await destinationStream.FlushAsync();
        imageArray = (await outputDecoder.GetPixelDataAsync()).DetachPixelData();
    }
    return imageArray;
}

Give that a try and see if it works out for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Ross, thanks for your reply. I've found another way to do this. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.