I'm using a TransformedBitmap
class to draw scaled images to a Bitmap
using TransformedBitmap.CopyPixels
. Is there a way to specify the scaling mode that is used? RenderOptions.SetBitmapScalingMode
doesn't seem to affect anything. I would like to use nearest neighbor but it appears to use a bi linear filter of some sort.
2 Answers
- It is not possible to specify the scaling algorithm, it is by design.
- The RenderOptions.SetBitmapScalingMode applies to rendering only, e.g. you have a 32*32 icon and want to show it at 256*256 but still in a blocky way (nearest neighbour)
Update
A few ways on how you could overcome this issue :
Do it by yourself : http://tech-algorithm.com/articles/nearest-neighbor-image-scaling/
Using Forms : https://stackoverflow.com/a/1856362/361899
Custom drawing : How to specify the image scaling algorithm used by a WPF Image?
There is AForge too but that might be overkill for your needs.
Update 2
WriteableBitmapEx will probably do the job easily for you : http://writeablebitmapex.codeplex.com/
You can resize a WriteableBitmap, specify interpolation mode and there is nearest neighbor.
Both TransformedBitmap and WriteableBitmapEx inherit from BitmapSource, likely you'll have no change to make at all to your existing code.
-
Interesting, do you have any suggestions for an alternative? (Given that I have a bitmapsource which needs to be scaled and copied to a Bitmap) – phosphoer Apr 05 '13 at 18:40
-
I've added a few ways for you in my answer. (sorry but I'm on my phone and it's not very practical) – aybe Apr 05 '13 at 23:42
-
1The WriteableBitmapEx looks like the thing to use, thank you! – phosphoer Apr 09 '13 at 18:38
public static class Extensions
{
public static BitmapFrame Resize(this
BitmapSource photo, int width, int height,
BitmapScalingMode scalingMode)
{
var group = new DrawingGroup();
RenderOptions.SetBitmapScalingMode(
group, scalingMode);
group.Children.Add(
new ImageDrawing(photo,
new Rect(0, 0, width, height)));
var targetVisual = new DrawingVisual();
var targetContext = targetVisual.RenderOpen();
targetContext.DrawDrawing(group);
var target = new RenderTargetBitmap(
width, height, 96, 96, PixelFormats.Default);
targetContext.Close();
target.Render(targetVisual);
var targetFrame = BitmapFrame.Create(target);
return targetFrame;
}
}
Took from http://weblogs.asp.net/bleroy/resizing-images-from-the-server-using-wpf-wic-instead-of-gdi

- 3,843
- 3
- 40
- 53