簡化代碼:
DrawingImage drawingElement = (DrawingImage)System.Windows.Application.Current.TryFindResource(name);
BitmapSource btmSrc = drawingElement as BitmapSource;
由於DrawingImage
不從的BitmapSource繼承,其結果將是空的。
我沒有DrawingImage
測試(所以把這個作爲一個僞不是一個複製粘貼的解決方案),但轉換的代碼應該是這個樣子:
// 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);
最後部分取自Is there a good way to convert between BitmapSource and Bitmap?
我們需要看到比這更多的代碼。什麼是「圖像」,它在哪裏定義? –