Search code examples
c#uwpwin2d

Scaling image using Bitmaptransform gives blured images in win2d


This is what I have tried:

var decoder = await BitmapDecoder.CreateAsync(fileStream);
BitmapTransform bitmapTransform = new BitmapTransform();
bitmapTransform.ScaledHeight = 300;
bitmapTransform.ScaledWidth = 800;

var pixelProvider = await decoder.GetPixelDataAsync(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    bitmapTransform,
                    ExifOrientationMode.IgnoreExifOrientation,
                    ColorManagementMode.DoNotColorManage);

byte[] by = pixelProvider.DetachPixelData();
CanvasBitmap cb = CanvasBitmap.CreateFromBytes(sender,by,800,300,Windows.Graphics.DirectX.DirectXPixelFormat.B8G8R8X8UIntNormalized);

What I have done in the Draw event of CanvasControl:

private  void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
args.DrawingSession.DrawImage(cb);
}

Due to scaling, the image gets blurred. How can I solve this issue? I need to change the width and height of image dynamically at run time, how can I do that? My Original Image: n

After Draw (Blured Image): enter image description here


Solution

  • When this happens, it means that your picture resolution exceeds the control size you have given. And the pixel aliasing is caused by the interpolation algorithm.

    By default, the interpolation algorithm used when the image is zoomed is Linear, if you want to render a larger resolution image on a smaller control, you can use the Fant algorithm.

    bitmapTransform.ScaledHeight = 300;
    bitmapTransform.ScaledWidth = 800;
    bitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
    

    If you plan to dynamically change the width and height of the picture, it is recommended to use ViewBox as the CanvasControl container.

    <Viewbox Stretch="Uniform" StretchDirection="Both" x:Name="MyViewbox">
        <xaml:CanvasControl />
    </Viewbox>
    

    Then you can change the size of the Viewbox at runtime.

    MyViewbox.Width = 400;
    MyViewbox.Height = 150;
    

    Thanks.