Dynamically crop a BitmapImage object

I have a BitmapImage object that contains a 600 X 400 image. Now from my C # code I need to create two new BitmapImage objects, for example objA and objB of 600 X 200 each, so objA contains the top cropped image, and objB contains bottom cropped image of the original image.

+4
source share
1 answer
BitmapSource topHalf = new CroppedBitmap(sourceBitmap, topRect); BitmapSource bottomHalf = new CroppedBitmap(sourceBitmap, bottomRect); 

The result is not a BitmapImage , but it is still a valid ImageSource , which should be OK if you just want to display it.


EDIT: There really is a way to do this, but it's pretty ugly ... You need to create an Image control with the original image and use the WriteableBitmap.Render method to render it.

 Image imageControl = new Image(); imageControl.Source = originalImage; // Required because the Image control is not part of the visual tree (see doc) Size size = new Size(originalImage.PixelWidth, originalImage.PixelHeight); imageControl.Measure(size); Rect rect = new Rect(new Point(0, 0), size); imageControl.Arrange(ref rect); WriteableBitmap topHalf = new WriteableBitmap(originalImage.PixelWidth, originalImage.PixelHeight / 2); WriteableBitmap bottomHalf = new WriteableBitmap(originalImage.PixelWidth, originalImage.PixelHeight / 2); Transform transform = new TranslateTransform(); topHalf.Render(originalImage, transform); transform.Y = originalImage.PixelHeight / 2; bottomHalf.Render(originalImage, transform); 

Disclaimer: This code is not fully verified;)

+5
source

All Articles