3

This is the continuation of

Datacontract serialization/serialization with images

so now I have a BitmapImage coming from a stream. In short a BitmapImage I want to resize it to a desired size.

I have found tons of code on how to resize from an image on file system but none on how to resize from an already existing BitmapImage

EDIT: enter image description here

Community
  • 1
  • 1
Luca
  • 918
  • 2
  • 13
  • 30

1 Answers1

11

You may use a TransformedBitmap with an appropriate ScaleTransform:

BitmapImage sourceBitmap = ...
var targetBitmap = new TransformedBitmap(sourceBitmap, new ScaleTransform(0.5, 0.5));

The result is a TransformedBitmap, not a BitmapImage. However, this shouldn't matter, because in your application there should be no need to deal only with BitmapImages. It should be sufficient to do all image-related stuff with the base classes BitmapSource or even ImageSource, which is the type of the Source property of the Image control.

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • TransformedBitmap wants a bitmapSource and not bitmapImage. It doesn't build and no easy cast is allowed – Luca Feb 29 '16 at 14:30
  • 1
    BitmapImage is derived from BitmapSource. You can pass a BitmapImage to every method that accepts a BitmapSource argument – Clemens Feb 29 '16 at 14:31
  • Please see my add. And then can Tranform use pixels instead than percent? – Luca Feb 29 '16 at 14:35
  • 3
    `targetBitmap` should be of type `BitmapSource`, not `BitmapImage`. – Clemens Feb 29 '16 at 14:39
  • The scale factors can be calculated by elementary math. Divide the desired width/height by the actual width/height of the source bitmap, as shown e.g. here: http://stackoverflow.com/a/18189949/1136211 – Clemens Feb 29 '16 at 14:58
  • So the problem is that: if I don't use the word ref for destination e.g. ResizeBmpSize(BitmapImage source, BitmapSource destination, int width, int height) the bmp is properly resized but not brought out of the s/r. If I use the word ref it get an error: Severity Code Description Project File Line Suppression State Error CS1503 Argument 2: cannot convert from 'ref System.Windows.Media.Imaging.BitmapImage' to 'ref System.Windows.Media.Imaging.BitmapSource' – Luca Feb 29 '16 at 15:03