Reputation: 4945
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;
Upvotes: 1
Views: 2167
Reputation: 17837
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?
Upvotes: 1