2011-08-01 20 views
1

なぜ、次のコードがbtmSrcに対してnullを返すのですか?あなたのコードの簡素化Image Controlから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から継承されていないので、結果は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?

+0

あなたは正しいです!私がそれをやろうとしていたのは、drawingElementからsystem.drawing.Bitmapを作成することでした。そうする方法はありますか? – Strider007

+0

drawingElementがnullではないことを確かめてください。そこにはDrawingImageの代わりにBitmapImageがあります(この場合、System.Drawing型への複数の変換が存在します)。しかし、それはリソース参照が失敗したことを意味します。スローされました。 –

+0

drawingElementがnullではありません。 xamlファイルに保存されているDrawingImageを取得しています。 DrawingImageをSystem.Drawingに変換するリンクやアイデアを私に提供してください。 – Strider007

関連する問題