1

why the following code is returning null for btmSrc ?

DrawingImage drawingElement =(DrawingImage)System.Windows.Application.Current.TryFindResource(name);
 System.Windows.Controls.Image image = new System.Windows.Controls.Image();
 image.Source = drawingElement as ImageSource;

BitmapSource btmSrc = image.Source as BitmapSource;
Strider007
  • 4,615
  • 7
  • 25
  • 26

1 Answers1

1

Simplifying your code :

DrawingImage drawingElement = (DrawingImage)System.Windows.Application.Current.TryFindResource(name);
BitmapSource btmSrc = drawingElement as BitmapSource;

As DrawingImage doesn't inherit from BitmapSource, the result will be null.


I don't have a DrawingImage to test (so take this as a pseudocode not as a copy-paste solution) but the conversion code should look something like this :

// Create a visual from a drawing
DrawingVisual drawingVisual = new DrawingVisual();
drawingVisual.Drawing.Children.Add(drawingImage.Drawing);

// Render it to a WPF bitmap
var renderTargetBitmap = new RenderTargetBitmap(
    drawingVisual.Drawing.Bounds.Right,
    drawingVisual.Drawing.Bounds.Bottom, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(drawingVisual);

// Create a bitmap with the correct size
Bitmap bmp = new Bitmap(renderTargetBitmap.PixelWidth,
    renderTargetBitmap.PixelHeight,  PixelFormat.Format32bppPArgb);
BitmapData data = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size),
    ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
renderTargetBitmap.CopyPixels(Int32Rect.Empty, data.Scan0,
    data.Height * data.Stride, data.Stride);
bmp.UnlockBits(data);

The last part being taken from Is there a good way to convert between BitmapSource and Bitmap?

Community
  • 1
  • 1
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
  • you are right! what i was trying to do it do create a system.drawing.Bitmap from the drawingElement. Is there a way to do so? – Strider007 Aug 01 '11 at 12:57
  • Are you sure that drawingElement is not null, i'll expect a BitmapImage instead of a DrawingImage there (and in this case multiple conversions to the System.Drawing types exists) but that would imply the the resource lookup failed because otherwise the cast would have thrown. – Julien Roncaglia Aug 01 '11 at 13:15
  • No drawingElement is not null. it is retrieving the DrawingImage that is saved in a xaml file. Please provide me with links or idea to convert DrawingImage to System.Drawing. – Strider007 Aug 01 '11 at 13:16