保存WPF画布图像画布、图像、WPF

2023-09-03 01:13:59 作者:我姓方却永远放不下她i

我在下面的这文章我得到了我的画布被保存,但是,我想延长code的功能和我的画布的特定部分保存为图像,而不是我的整个画布。

I was following this article and I got my canvas to be saved, however, I want to extend the code's functionality and save a particular part of my canvas as an image, rather than my entire canvas.

我尝试设置 rect.Offset rect.Location 属性,但图像始终保存从上我的画布的左上角。

I tried setting the rect.Offset and rect.Location properties but the image is always saved from the upper left corner of my canvas.

有谁知道我可以实现我想要的功能,以类似的方式?

Does anyone know how can I achieve my wanted functionality in a similar way?

谢谢!

推荐答案

一个简单的方法是使用一个CroppedBitmap经过渲染整个画布。如果你需要多张图片,你可以重复使用相同的RenderTargetBitmap。

A simple method would be to use a CroppedBitmap after rendering the whole canvas. You could reuse the same RenderTargetBitmap if you need multiple images.

RenderTargetBitmap rtb = new RenderTargetBitmap((int)canvas.RenderSize.Width,
    (int)canvas.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
rtb.Render(canvas);

var crop = new CroppedBitmap(rtb, new Int32Rect(50, 50, 250, 250));

BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(crop));

using(var fs = System.IO.File.OpenWrite("logo.png"))
{
    pngEncoder.Save(fs);
}