Resize image in xaml without losing quality
I have this image (original size: 256x256)
I made this xaml definition to show the image in my application
<Image Grid.Row="1"
Source="/MyProject;component/Images/happy.png"
Stretch="Fill"
Width="64" Height="64"
VerticalAlignment="Top" Margin="0,0,0,0"
HorizontalAlignment="Center" />
And I get this result
How can I made a more smooth resize?
Include RenderOptions.BitmapScalingMode="Fant"
on your Image, like so:
<Image Grid.Row="1"
Source="/MyProject;component/Images/happy.png"
RenderOptions.BitmapScalingMode="Fant"
Stretch="Fill"
Width="64"
Height="64"
VerticalAlignment="Top"
Margin="0,0,0,0"
HorizontalAlignment="Center" />
Set RenderOptions.BitmapScalingMode
property for your Image
through .xaml
:
<Image Grid.Row="1" RenderOptions.BitmapScalingMode="HighQuality" ... />
Additional info:
The RenderOptions.BitmapScalingMode
is a property that scales the images based on the quality.
WPF 4.0 defaults it to Unspecified
, which refers to LowQuality
image rendering.
But to ensure that the image remains good quality when the size increases, BitmapScalingMode
should be chosen as HighQuality
.
Here is BitmapScalingMode Enumeration members with their description from msdn:
1.Fant - Use very high quality Fant bitmap scaling, which is slower than all other bitmap scaling modes, but produces higher quality output.
2.HighQuality - Use high quality bitmap scaling, which is slower than LowQuality mode, but produces higher quality output. The HighQuality mode is the same as the Fant mode.
3.Linear - Use linear bitmap scaling, which is faster than HighQuality mode, but produces lower quality output.
4.LowQuality - Use bilinear bitmap scaling, which is faster than HighQuality mode, but produces lower quality output. The LowQuality mode is the same as the Linear mode.
5.NearestNeighbor - Use nearest-neighbor bitmap scaling, which provides performance benefits over LowQuality mode when the software rasterizer is used. This mode is often used to magnify a bitmap.
6.Unspecified - Use the default bitmap scaling mode, which is Linear.
As answered above, the setting RenderOptions.BitmapScalingMode="HighQuality"
activates the antialiasing. I'd like to provide an example for users who don't know what antialiasing is.
Without this setting :
<Image x:Name="InstrumentImage" />
With this setting :
<Image x:Name="InstrumentImage" RenderOptions.BitmapScalingMode="HighQuality" />
See the different options here : https://docs.microsoft.com/en-us/dotnet/api/system.windows.media.bitmapscalingmode?view=netframework-4.8