Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Poorly Downscaled Jpeg Image using C#

Tags:

c#

image

I'm trying to downscale a jpeg image from 3028x4051 to 854x1171. This results in an image which is close to 1M pixels and maintains the aspect ratio. The original image is here. The image scales down very poorly though. Below is a section of the image. The top is the image scaled down in MS paint, the bottom it is scaled down programatically in C#. I've included the code I've used to downscale and save it. Anyone know what could be going on?

enter image description here

using (IRandomAccessStream sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
{
    BitmapDecoder myDecoder = await GetDecoder(sourceStream);
    BitmapTransform myTransform = new BitmapTransform() { ScaledHeight = h, ScaledWidth = w };
    await myDecoder.GetPixelDataAsync(
            BitmapPixelFormat.Rgba8,
            BitmapAlphaMode.Premultiplied,
            myTransform,
            ExifOrientationMode.IgnoreExifOrientation,
            ColorManagementMode.DoNotColorManage);
    BitmapEncoder myEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);
            myEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixelData.DetachPixelData());
    await myEncoder.FlushAsync();
}
like image 627
kernanb Avatar asked Mar 17 '26 20:03

kernanb


1 Answers

Where you create a new instance of BitmapTransform, you can specify the interpolation mode. Linear is the default mode, so to get a better result you need to try with Cubic or Fant.

using (IRandomAccessStream sourceStream = await sourceFile.OpenAsync(FileAccessMode.Read))
{
    BitmapDecoder myDecoder = await GetDecoder(sourceStream);
    BitmapTransform myTransform = new BitmapTransform() { ScaledHeight = h, ScaledWidth = w, InterpolationMode = BitmapInterpolationMode.Fant };
    await myDecoder.GetPixelDataAsync(
            BitmapPixelFormat.Rgba8,
            BitmapAlphaMode.Premultiplied,
            myTransform,
            ExifOrientationMode.IgnoreExifOrientation,
            ColorManagementMode.DoNotColorManage);
    BitmapEncoder myEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream);
            myEncoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixelData.DetachPixelData());
    await myEncoder.FlushAsync();
}
like image 136
Blas Soriano Avatar answered Mar 20 '26 10:03

Blas Soriano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!