Click here to Skip to main content
15,889,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

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


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!
Posted
Comments
Richard MacCutchan 22-Sep-13 3:23am    
The error is quite clear, a DrawingImage is not related to a BitmapSource, so you cannot cast it. You need to find a method that will convert it.
Richard MacCutchan 22-Sep-13 7:17am    
Try a Google search and see what hits you get.
Richard MacCutchan 22-Sep-13 7:44am    
And being too lazy to do your own research is not very constructive either.
Richard MacCutchan 22-Sep-13 8:47am    
It certaibnly wasn't obvious from your question which implies that you do not understand the difference between casting and converting. As to the actual Google search, how is it that you did not find any of these links, which suggest more than one way to do it?

1 solution

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:
C#
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;
}


To DrawingImage:
C#
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);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900