2009年7月24日 星期五

在WPF中存讀圖檔

要把WPF的物件輸出成圖檔
首先將視覺化物件先繪製出來
透過一個encoder將繪製出的圖檔編碼
最後再透過filestream將圖存進檔案

private void SaveTo(Visual v, string f)
{
/// get bound of the visual
Rect b = VisualTreeHelper.GetDescendantBounds(v);

/// new a RenderTargetBitmap with actual size
RenderTargetBitmap r = new RenderTargetBitmap(
(int)b.Width, (int)b.Height,
96, 96, PixelFormats.Pbgra32);

/// render visual
r.Render(v);

/// new a JpegBitmapEncoder and add r into it
JpegBitmapEncoder e = new JpegBitmapEncoder();
e.Frames.Add(BitmapFrame.Create(r));

/// new a FileStream to write the image file
FileStream s = new FileStream(f,
FileMode.OpenOrCreate, FileAccess.Write);
e.Save(s);
s.Close();
}

記得這時候想要輸出的控制項和其父控制項的左上角必須對齊
可參考在WPF中存圖檔的問題(RenderTargetBitmap)

另外,如果要從檔案中讀出圖檔並放進WPF的畫布(Canvas)上面的話
則是先從一個filestream將檔案打開
並透過decoder將圖檔解碼

private void LoadFrom(Canvas c, string f)
{
/// new a FileStream to write the image file
FileStream s = new FileStream(f,
FileMode.OpenOrCreate, FileAccess.Read);

/// new a decoder to decode image
BitmapDecoder d = BitmapDecoder.Create(s,
BitmapCreateOptions.None,
BitmapCacheOption.None);

/// new an image with decoded image
Image i = new Image();
i.Source = d.Frames[0];

/// add the image into canvas
c.Children.Add(i);
}

注意,此時如果將FileStream關掉(Close)的話
會丟出影響無法解碼的例外情形
所以要等到該圖已經不在需要顯示的時候再做Close的動作

沒有留言:

張貼留言