How to resize an image using UWP?

0

I have this 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 uploading to the blob.

this :

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

Remembering that with UWP (applications for windows 10), you can not use System.Drawing.Image.

    

asked by anonymous 07.10.2016 / 13:30

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 pixel buffer of the image to generate another buffer, which can be used to create a new image.

    
24.02.2017 / 17:55