2011-08-01 27 views
1

爲什麼下面的代碼對於btmSrc返回null?從圖像控件獲取BitmapSource

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繼承,其結果將是空的。


我沒有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?

+0

你是對的!我試圖做的事情是從drawingElement創建一個system.drawing.Bitmap。有沒有辦法做到這一點? – Strider007

+0

您確定drawingElement不爲空,我期望BitmapImage代替DrawingImage(在這種情況下,存在對System.Drawing類型的多次轉換),但這意味着資源查找失敗,因爲否則轉換會拋出。 –

+0

沒有drawingElement不爲null。它正在檢索保存在xaml文件中的DrawingImage。請爲我提供鏈接或想法將DrawingImage轉換爲System.Drawing。 – Strider007