Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nearest Neighbor rendering in UWP

Tags:

c#

graphics

uwp

I'm trying to zoom images in UWP by using nearest neighbor scaling. In WPF i used RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor);. How can I get the same result but in UWP?

EXAMPLE

like image 939
Omer Avatar asked Sep 11 '25 23:09

Omer


1 Answers

In WPF i used RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.NearestNeighbor);. How can I get the same result but in UWP?

In uwp, BitmapTransform can be used for scaling images. To getting the same effects as you got by using BitmapScalingMode.NearestNeighbor in WPF, you need to use BitmapInterpolationMode which has NearestNeighbor value.

Example code you can reference follows:

private async Task<IStorageFile> CreateNewImage(StorageFile sourceFile, int requestedMinSide, StorageFile resizedImageFile)
{
    var imageStream = await sourceFile.OpenReadAsync();
    var decoder = await BitmapDecoder.CreateAsync(imageStream);
    var originalPixelWidth = decoder.PixelWidth;
    var originalPixelHeight = decoder.PixelHeight;
    using (imageStream)
    {
        using (var resizedStream = await resizedImageFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            var encoder = await BitmapEncoder.CreateForTranscodingAsync(resizedStream, decoder);
            double widthRatio = (double)requestedMinSide / originalPixelWidth;
            double heightRatio = (double)requestedMinSide / originalPixelHeight;
            uint aspectHeight = (uint)requestedMinSide;
            uint aspectWidth = (uint)requestedMinSide;
            uint cropX = 0, cropY = 0;
            var scaledSize = (uint)requestedMinSide;
            aspectHeight = (uint)(widthRatio * originalPixelHeight);
            cropY = (aspectHeight - aspectWidth) / 2;
            encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.NearestNeighbor;
            encoder.BitmapTransform.ScaledHeight = aspectHeight;
            encoder.BitmapTransform.ScaledWidth = aspectWidth;
            encoder.BitmapTransform.Bounds = new BitmapBounds()
            {
                Width = scaledSize,
                Height = scaledSize,
                X = cropX,
                Y = cropY,
            };
            await encoder.FlushAsync();
        }
    }
    return resizedImageFile;
}
like image 188
Sunteen Wu Avatar answered Sep 13 '25 12:09

Sunteen Wu