How to resize an image using UWP?

Asked

Viewed 61 times

0

I have that code:

var file = await ImageChooser.GetSelectedImageAsStorageFile();

var sasUri = await Vm.GetBlobSasUri(file.Name);

var blob = await file.UploadToBlob(sasUri);

await Vm.ImageSelected(blob.Uri);

I need to resize the image before going up to the blob.

I tried that:

But the problem is that the function returns a bitmap, and in my case it is not necessary a copy.

Remember that with UWP (windows 10 apps), you cannot use System.Drawing.Image.

1 answer

1

You can use this function.


public async Task 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];
            await resizedStream.ReadAsync(outBuffer.AsBuffer(), (uint)resizedStream.Size, InputStreamOptions.None);
            return outBuffer;
        }
    }
    return imageData;
}

It will use the image pixels buffer to generate another buffer, which can be used to create a new image.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.