我正在尝试使用CroppedBitmap
类在WPF应用程序StageWindow.Stage
中裁剪BitmapImage
。
将新裁剪的图像保存到文件JpegBitmapEncoder
时,我可以看到正确裁剪的图像。CroppedBitmap Crop
然而,我实际上想将裁剪后的图像保存到List<BitmapImage>
中,以便稍后在另一个WPF图像控件中使用。该列表已经包含BitmapImages
,因此将其更改为CroppedBitmaps
是不够的。
为了能够存储新的croppedBitmap,我使用了这样的东西:
BitmapImage xx = CroppedBitmap1 as BitmapImage;
将WPF图像控件设置为new BitmapImage
(ExpectedCroppedImage(时,它仍然显示不带裁剪的CroppedBitmaps
原始源图像。
我怀疑上面的代码从新的BitmapImage
中删除了裁剪属性,因为BitmapImage
本身没有裁剪区域的属性。但是,我如何才能仅将裁剪的部分保存到新的BitmapImage
中呢?
我一直在四处搜索,但似乎CroppedBitmap应该做到这一点,我只是不知道如何以正确的方式将其转换回来。
以下是需要澄清的代码:
//Stage is the WPF image element that im reading the source image from.
ImageSource StageWindowImageSource = StageWindow.Stage.Source;
CroppedBitmap Crop = new CroppedBitmap((BitmapSource)StageWindowImageSource, new Int32Rect(0,0,50,50));
ExpectedCroppedImage = Crop.Source as BitmapImage;
JpegBitmapEncoder jpg = new JpegBitmapEncoder();
jpg.Frames.Add(BitmapFrame.Create(Crop));
FileStream fp = new FileStream("F:/Crop.jpg", FileMode.Create, FileAccess.Write);
jpg.Save(fp);
fp.Close();
行
ExpectedCroppedImage = Crop.Source as BitmapImage;
不返回裁剪的位图,而是从中获取裁剪的原始位图,即Source
位图。
除此之外,您不需要从CroppedBitmap
到BitmapImage
的任何转换。
相反,使用BitmapImage和CroppedBitmap的基类作为List的元素类型,即为集合使用List<BitmapSource>
或List<ImageSource>
。
现在,您可以分配从元素类型派生的任何类的实例。
List<BitmapSource> images = ...
CroppedBitmap croppedImage = new CroppedBitmap(...);
images.Add(croppedImage);
BitmapImage someOtherImage = new BitmapImage(...);
images.Add(someOtherImage);
private void MyMethod()
{
ImageSource StageWindowImageSource = img.Source;
CroppedBitmap Crop = new CroppedBitmap((BitmapSource) StageWindowImageSource, new Int32Rect(20, 20, 150, 110));
img2.Source = GetImage(Crop, new JpegBitmapEncoder());
}
private BitmapImage GetImage(BitmapSource source, BitmapEncoder encoder)
{
var image = new BitmapImage();
using (var sourceMs = new MemoryStream())
{
encoder.Frames.Add(BitmapFrame.Create(source));
encoder.Save(sourceMs);
sourceMs.Position = 0;
using (var destMs = new MemoryStream(sourceMs.ToArray()))
{
image.BeginInit();
image.StreamSource = destMs;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
image.Freeze();
}
}
return image;
}