phosphoer
phosphoer

Reputation: 443

TransformedBitmap Scaling Mode

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.

Upvotes: 2

Views: 3321

Answers (2)

Andreas
Andreas

Reputation: 4013

 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

Upvotes: 1

aybe
aybe

Reputation: 16682

  • 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.

Upvotes: 3

Related Questions