无法将类型'System.Windows.Media.DrawingImage'转换为'System.Windows.Media.Imaging.BitmapSource' [英] Cannot convert type 'System.Windows.Media.DrawingImage' to 'System.Windows.Media.Imaging.BitmapSource'

查看:357
本文介绍了无法将类型'System.Windows.Media.DrawingImage'转换为'System.Windows.Media.Imaging.BitmapSource'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试从System.Windows.Media.Drawing图像创建位图源。有人可以帮助,不知道如何转换。这是我的代码:



Hi,

I am trying to create a bitmap source from a System.Windows.Media.Drawing image. Can someone help, not sure how to convert. Here's my code:

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)imgsrc.Source));
using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                    encoder.Save(stream);





当我的imgsrc是使用位图源创建的时,上面的代码工作良好。但是当我的imgsrc对象是使用DrawingImage对象创建的时,抛出异常说:



无法将类型为'System.Windows.Media.DrawingImage'的对象强制转换为输入'System.Windows.Media.Imaging.BitmapSource'。



提前致谢!



When my imgsrc is one that has been created using a bitmap source, the code above works fine. BUT when my imgsrc object was created using a DrawingImage object, an exception is thrown saying:

Unable to cast object of type 'System.Windows.Media.DrawingImage' to type 'System.Windows.Media.Imaging.BitmapSource'.

Thanks in advance!

推荐答案

对于其他任何需要手工操作的人,我创建了两种扩展方法来在DrawingImage和BitmapSource之间前后转换:



到BitmapSource:

For anyone else that needs a hand working this out, I created two extension methods to convert back and forward between DrawingImage and BitmapSource:

To BitmapSource:
public static BitmapSource ToBitmapSource(this DrawingImage source)
{
     DrawingVisual drawingVisual = new DrawingVisual();
     DrawingContext drawingContext = drawingVisual.RenderOpen();
     drawingContext.DrawImage(source, new Rect(new Point(0, 0), new Size(source.Width, source.Height)));
     drawingContext.Close();

     RenderTargetBitmap bmp = new RenderTargetBitmap((int)source.Width, (int)source.Height, 96, 96, PixelFormats.Pbgra32);
     bmp.Render(drawingVisual);
     return bmp;
}





到DrawingImage:



To DrawingImage:

public static DrawingImage ToDrawingImage(this BitmapSource source)
{
     Rect imageRect = new Rect(0, 0, source.PixelWidth, source.PixelHeight);
     ImageDrawing drawing = new ImageDrawing(source, imageRect);
     return new DrawingImage(drawing);
}


这篇关于无法将类型'System.Windows.Media.DrawingImage'转换为'System.Windows.Media.Imaging.BitmapSource'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆