Dynamically crop a BitmapImage object

rohits picture rohits · Sep 25, 2010 · Viewed 8.7k times · Source

I have a BitmapImage object that contains an image of 600 X 400 dimensions. Now from my C# code behind, I need to create two new BitmapImage objects, say objA and objB of dimensions 600 X 200 each such that objA contains the upper half cropped image and objB contains the lower half cropped image of the original image.

Answer

Thomas Levesque picture Thomas Levesque · Sep 25, 2010
BitmapSource topHalf = new CroppedBitmap(sourceBitmap, topRect);
BitmapSource bottomHalf = new CroppedBitmap(sourceBitmap, bottomRect);

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


EDIT: actually there is a way to do it, 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 completely untested ;)