UWP: How to resize an Image

Viewed 6766

I have a JPEG image stored in a Byte[] that I want to resize. This is my code:

public async Task<byte[]> ResizeImage(byte[] imageData, int reqWidth, int reqHeight, int quality)
{

    var memStream = new MemoryStream(imageData);

    IRandomAccessStream imageStream = memStream.AsRandomAccessStream();
    var decoder = await BitmapDecoder.CreateAsync(imageStream);
    if (decoder.PixelHeight > reqHeight || decoder.PixelWidth > reqWidth)
    {
        using (imageStream)
        {
            var resizedStream = new InMemoryRandomAccessStream();

            BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
            double widthRatio = (double) reqWidth/decoder.PixelWidth;
            double heightRatio = (double) reqHeight/decoder.PixelHeight;

            double scaleRatio = Math.Min(widthRatio, heightRatio);

            if (reqWidth == 0)
                scaleRatio = heightRatio;

            if (reqHeight == 0)
                scaleRatio = widthRatio;

            uint aspectHeight = (uint) Math.Floor(decoder.PixelHeight*scaleRatio);
            uint aspectWidth = (uint) Math.Floor(decoder.PixelWidth*scaleRatio);

            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Linear;

            encoder.BitmapTransform.ScaledHeight = aspectHeight;
            encoder.BitmapTransform.ScaledWidth = aspectWidth;

            await encoder.FlushAsync();
            resizedStream.Seek(0);
            var outBuffer = new byte[resizedStream.Size];
            uint x =  await resizedStream.WriteAsync(outBuffer.AsBuffer());
            return outBuffer;
        }
    }
    return imageData;
}

The problem is that outBuffer just contains zeros although the correct number of Bytes have been written.

2 Answers
Related