【问题标题】:How to combine an array of png images like layers using C#?如何使用 C# 组合一组 png 图像,如图层?
【发布时间】:2011-07-24 20:02:00
【问题描述】:

我有一个名为

的图像数组
image_<somenumber>_trans.png

所有这些图像都有透明区域。这个想法是,当把一个放在一起时 他们将形成一个漂亮的形象。但是我收到了一个奇怪的与 GDI+ 相关的错误(“GDI+ 中发生了一般错误”) 我已经疯了。我现在使用的代码如下图所示;

number_of_photos = 30;
Bitmap temp = new Bitmap("background.png");//some white background 640x480 pixels
temp.Save("temp.png", ImageFormat.Png);
temp.Dispose();
for (int photo_no = 0; photo_no < number_of_photos; photo_no++)
{
    Bitmap temp1 = new Bitmap("temp.png");
    Graphics gra = Graphics.FromImage(temp1);
    Bitmap new_layer = new Bitmap("image_" + photo_no + "_trans.png");
    //the images image_<photo_no>_trans.png are also 640x480 pixels
    gra.DrawImage(new_layer,0,0);
    temp1.Save("temp.png");//error: A generic error occurred in GDI+.
    temp1.Dispose();
 }

我做错了吗?提前感谢您的帮助...

【问题讨论】:

  • 我认为您可以通过将Graphics 实例移到for 循环之外来重用它。
  • 包含“奇怪的 GDI+ 相关错误”的 exact 文本将非常有助于您获得有用的答案。
  • 异常中还有细节吗?是否每次都使用相同的图像,或者您可以尝试使用不同的图像并使其工作(即,从图像 1 而不是图像 0 开始,并且仍然除外)
  • @Donal 我已经写过的错误是“GDI+ 中发生一般错误。”
  • John:我冒昧地在您问题的文本部分中包含该消息,因为它已经存在并不是很明显。

标签: c# image png overlay layer


【解决方案1】:

我的建议是仅在整个过程完成后保存图像。

Image i = new Image(...)
Graphics g = Graphics.FromImage(i)
for(...)
{
    g.Draw(...)
}

i.Save(...)

【讨论】:

  • 比我得到一个An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll Additional information: A generic error occurred in GDI+. 错误
  • 好的,找到问题了。我也使用了一些@slaks 评论
【解决方案2】:

写入new Bitmap(filename) 将锁定文件,直到您处置Bitmap
因此,您无法覆盖该文件。

【讨论】:

  • 要么将文件加载到 MemoryStream 中,然后从中创建一个 Image,要么另存为其他名称。
  • 每次迭代都需要重新保存图像吗?不能完成编译再保存位图吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
  • 2015-12-18
  • 2018-05-03
  • 2023-03-17
相关资源
最近更新 更多