how do i resize and reduce size using a compression quality value in xamarinuwp?

Got it figured out eventually, I used to code below to achieve this.

public async Task<byte[]> DecodeImageAsync(string fileUri, int regWidth, int regHeight, int compressionQuality)
    byte[] returnVal;

        StorageFile file = await StorageFile.GetFileFromPathAsync(fileUri);

        using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
            SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

            var qualityNum = (float) compressionQuality / 100;
            var propertySet = new BitmapPropertySet();
            var qualityValue = new BitmapTypedValue(
            propertySet.Add("ImageQuality", qualityValue);

            var resizedStream = new InMemoryRandomAccessStream();

            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, resizedStream,
            double widthRatio = (double) regWidth / decoder.PixelWidth;
            double heightRatio = (double) regHeight / decoder.PixelHeight;

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

            if (regWidth == 0)
                scaleRatio = heightRatio;

            if (regHeight == 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();
            returnVal = new byte[resizedStream.Size];
            var dr = new DataReader(resizedStream.GetInputStreamAt(0));
            await dr.LoadAsync((uint) resizedStream.Size);
    }catch (Exception ex)
        return null;
    return returnVal;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top