我以前看到过有关此问题的线程,但我似乎无法找到解决我的问题的方法。我有一个允许用户创建自己的画布的应用程序。假设在这个例子中,用户创建了 150 个 745px x 1045px 的画布。现在有一个功能允许用户将这些全部导出到单独的 PNG 文件中。这是我的方法:
public static void ExportToPng(Uri path, Canvas surface)
{
if (path == null) return;
Size size = new Size(surface.Width, surface.Height);
surface.Measure(size);
surface.Arrange(new Rect(size));
surface.UpdateLayout();
RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(surface);
using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(outStream);
}
}
在大约 45 张左右的图像之后,应用程序中断了:renderBitmap.Render(surface); 说: 内存不足,无法继续执行程序。
现在我明白这个过程可能有点占用内存,但我觉得在图像被渲染并导出为 PNG 之后,我应该能够以某种方式处理它,然后再转到下一张图像。我只是不知道该怎么做。任何和所有的建议表示赞赏!