2009-02-26 5 views
7

私はこの問題に関するいくつかの質問を投稿しましたが、これはできないと信じ始めています。ここは裏話です。WP32で実行時にイメージをレンダリングする

私には、.pngイメージを生成するASP.NETアプリケーションがあります。この.pngイメージは、XAMLまたはWPFビジュアルツリーから構築する必要があります。このため、STAスレッドで.pngイメージを生成する必要があります。私のXAML/WPFビジュアルツリーにImageが含まれるまで(System.Windows.Controls.Imageのように)すべてが正常に動作します。画像要素が参照画像を表示しない限り、私の.pngファイルが正しく生成されます。参照先のピクチャは、リモートURLにあります。エラーや例外はスローされません。

System.Windows.Controls.Image要素を含むXAML/WPFビジュアルツリーから.pngイメージを作成するにはどうすればよいですか?結果の.pngには、Image要素で参照される画像が含まれている必要があります。さまざまな方法で次のコードを試しました。

string address = "http://imgtops.sourceforge.net/bakeoff/o-png24.png"; 

WebClient webClient = new WebClient(); 
byte[] imageContent = webClient.DownloadData(address); 

Image image = new Image(); 
using (MemoryStream memoryStream = new MemoryStream(imageContent)) 
{ 
    BitmapImage imageSource = new BitmapImage(); 
    imageSource.BeginInit(); 
    imageSource.StreamSource = memoryStream; 
    imageSource.EndInit(); 
    image.Source = imageSource; 
} 

// Set the size 
image.Height = 200; 
image.Width = 300; 

// Position the Image within a Canvas 
image.SetValue(Canvas.TopProperty, 1.0); 
image.SetValue(Canvas.LeftProperty, 1.0); 

Canvas canvas = new Canvas(); 
canvas.Height = 200; 
canvas.Width = 300; 
canvas.Background = new SolidColorBrush(Colors.Purple); 
canvas.Children.Add(image); 

// Create the area 
Size availableSize = new Size(300, 200); 
frameworkElement.Measure(availableSize); 
frameworkElement.Arrange(new Rect(availableSize)); 

// Convert the WPF representation to a PNG file    
BitmapSource bitmap = RenderToBitmap(frameworkElement); 
PngBitmapEncoder encoder = new PngBitmapEncoder(); 
encoder.Frames.Add(BitmapFrame.Create(bitmap)); 

// Generate the .png 
FileStream fileStream = new FileStream(filename, FileMode.Create); 
encoder.Save(fileStream); 


public BitmapSource RenderToBitmap(FrameworkElement target) 
{ 
    int actualWidth = 300; 
    int actualHeight = 200; 

    Rect boundary = VisualTreeHelper.GetDescendantBounds(target); 
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(actualWidth, actualHeight, 96, 96, PixelFormats.Pbgra32); 

    DrawingVisual drawingVisual = new DrawingVisual(); 
    using (DrawingContext context = drawingVisual.RenderOpen()) 
    { 
    VisualBrush visualBrush = new VisualBrush(target); 
    context.DrawRectangle(visualBrush, null, new Rect(new Point(), boundary.Size)); 
    } 

    renderBitmap.Render(drawingVisual); 
    return renderBitmap; 
} 

ありがとうございました。

+1

質問に答えなくても、私が持っていたのと同じ質問に走ってくれてありがとうと感謝します。 –

答えて

14

出力ビットマップを正しくレンダリングしています。これは、入力したビットマップだけです。

BitmapImageは、DownloadCompletedイベントが発生するまでStreamSourceプロパティにアクセスする必要がありますが、MemoryStreamの '使用'ブロックDispose()にはチャンスがあります。あなたは単純にusingブロックからMemoryStreamのラップを解除してGCに処理させることができます(そうした場合、BitmapImage.CacheOptionをBitmapCacheOption.Noneに設定して、ストリームをコピーではなく直接使用することをお勧めします)。 UriSourceプロパティを使用し、レンダリングする前にDownloadCompleteイベントを待機します。

+1

ありがとうございました!これは私の問題を完全に解決しました。私はナッツに行っていた。 – user70192

+0

完璧!この答えを提供してくれてありがとう! –

関連する問題