动态裁剪一个BitmapImage对象

4

我有一个BitmapImage对象,其中包含600 X 400像素的图像。现在从我的C#代码中,我需要创建两个新的BitmapImage对象,即objA和objB,每个对象的尺寸为600 X 200,其中objA包含裁剪后的上半部分图像,objB包含原始图像的裁剪后的下半部分图像。

1个回答

5
BitmapSource topHalf = new CroppedBitmap(sourceBitmap, topRect);
BitmapSource bottomHalf = new CroppedBitmap(sourceBitmap, bottomRect);

结果不是BitmapImage,但它仍然是有效的ImageSource,如果您只想显示它,这应该没问题。
编辑:实际上有一种方法可以做到这一点,但它非常丑陋...您需要创建一个带有原始图像的Image控件,并使用WriteableBitmap.Render方法进行渲染。
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);

免责声明:此代码完全未经测试 ;)

谢谢,但我需要在Silverlight应用程序中使用这段代码,而且我找不到添加CroppedBitmap引用的方法。因此,你的答案对我没有帮助。 - rohits
我刚刚查看了SL文档。 显然它甚至没有DrawingContext类,所以我怀疑你不能轻松地在SL中完成这个... 你可能需要第三方组件。 - Thomas Levesque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接