How to combine an array of png images like layers using C#?

℡╲_俬逩灬. 提交于 2019-12-08 00:45:01

问题


I have an array of images named

image_<somenumber>_trans.png

All these images have transparent areas. The idea is that when put one on top each other they will form a nice looking image. But I have been getting a weird GDI+ related error (“A generic error occurred in GDI+”) and I have been going crazy. The code I'm using now can be viewed as below;

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();
 }

Am I doing something wrong? Thank you for your help in advance...


回答1:


My suggestion is to only save the image when the whole process is completed.

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

i.Save(...)



回答2:


Writing new Bitmap(filename) will lock the file until you dispose the Bitmap.
Therefore, you can't overwrite the file.



来源:https://stackoverflow.com/questions/6809309/how-to-combine-an-array-of-png-images-like-layers-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!