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.
+1
A:
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 ;)
Thomas Levesque
2010-09-25 14:49:02
Thanks, but I need to use the code for a Silverlight application and I am not getting a way to add reference to CroppedBitmap. Hence your answer is not helping me.
rohits
2010-09-27 05:53:28
Sorry, I didn't realize this class doesn't exist in SL...
Thomas Levesque
2010-09-27 07:40:58
I just had a look at the SL documentation. Apparently it doesn't even have the DrawingContext class, so I doubt you can easily do this in SL... You will probably need 3rd party components
Thomas Levesque
2010-09-27 18:21:15
Actually I just thought of something, see my updated answer
Thomas Levesque
2010-09-27 18:36:17