簡體   English   中英

使用 RenderTargetBitmap 保存部分顯示的圖像

[英]Using RenderTargetBitmap to save a portion of the displayed images

我有一個簡單的 WPF 應用程序,我在其中顯示一個非常大的圖像 (9000x2875),在它上面顯示許多小圖像 (64x64)。

為此,我有一個Canvas和一個Image ,然后我在小圖像到達時以編程方式添加它們。

現在我正在嘗試將部分合成圖像保存為png文件。 我想我會使用RenderTargetBitmap來渲染我想要的Canvas部分。 我的問題是我找不到保存圖像正確部分的好方法。 這是我目前的黑客:

private static void SaveImage(Canvas canvas, string file, int x, int y, int width, int height)
{
  //changing 0,0 on the canvas so RenderTargetBitmap works as expected.
  canvas.RenderTransform = new MatrixTransform(1d, 0d, 0d, 1d, -x, -y);
  canvas.UpdateLayout();
  RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 96d, 96d, Pixelformats.Pbgra32);
  bmp.Render(canvas);
  PngBitmapEncoder encoder = new PngBitmapEncoder();
  encoder.Frames.Add(BitmapFrame.Create(bmp));
  using(Stream s = File.Create(file))
  {
    encoder.Save(s);
  }
}

明顯的問題是顯示會因RenderTransform而改變。 它還使應用程序變慢。 我確實嘗試過對整個 canvas 進行 RenderTargetBitmap,但這比這樣做要慢得多。

所以我的問題是:
有沒有更簡單的方法來保存查看的圖像的一部分?
如果沒有,有人對 go 有更好的建議嗎? (我已經嘗試過單個WriteableBitmap ,但這與整個 canvas 的RenderTargetBitmap一樣慢。

您要使用的是CroppedBitmap ,它將允許您保存圖像的裁剪部分。

// (BitmapSource bmps)
CroppedBitmap crop = new CroppedBitmap(bmps, new Int32Rect(selRect.X, selRect.Y, selRect.Width, selRect.Height));

編輯:由於似乎沒有辦法讓它在 WPF 中按照您想要的方式執行,我建議使用 GDI+ 預先裁剪大圖像(不顯示它)並將您想要的區域加載到較小的 canvas 上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM