为什么以下代码为btmSrc返回null?
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;
答案 0 :(得分:1)
简化您的代码:
DrawingImage drawingElement = (DrawingImage)System.Windows.Application.Current.TryFindResource(name);
BitmapSource btmSrc = drawingElement as BitmapSource;
由于DrawingImage
不从BitmapSource继承,结果将为null。
我没有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?