overlaying images with GDI+

时光总嘲笑我的痴心妄想 提交于 2019-12-25 03:46:32

问题


I'm trying to overlay a image with a couple of other images. I use this code to do that:

Dim gbkn As Bitmap = New Bitmap(7001, 7001, Imaging.PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(CType(gbkn, Image))
g.DrawImage(Image.FromFile("C:\background.png"), New Point(0, 0))
g.DrawImage(Image.FromFile("C:\firstlayer.png"), New Point(0, 0))
g.DrawImage(Image.FromFile("C:\secondlayer.png"), New Point(0, 0))

This works with the first two pictures. After that an OutOfMemoryException is thrown. I realize the size of the images are large. But isn't it somehow possible to do the overlays and chache them somewhere?

Even if I save the result of the first overlay to disk, free memory, and add another layer I still get the exception.

How should I approach this problem?

JosP


回答1:


Don't know if this is actually the problem, but you are not disposing of the images that you are drawing on the bitmap. Does this help?

Dim gbkn As Bitmap = New Bitmap(7001, 7001, Imaging.PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(CType(gbkn, Image))
Dim img As Image = Image.FromFile("C:\background.png")
g.DrawImage(img, New Point(0, 0))
img.Dipose()
img As Image = Image.FromFile("C:\firstlayer.png")
g.DrawImage(img, New Point(0, 0))
img.Dispose()
img As Image = Image.FromFile("C:\secondlayer.png")
g.DrawImage(Image.FromFile("C:\secondlayer.png"), New Point(0, 0))
img.Dispose()

I seriously doubt it has anything to do with the images, as I have worked with images 2-3 times that size without that problem. Also OutOfMemoryError exception seems to be one of the <sarcasm>extremely useful</sarcasm> errors that GDI throws that frequently has nothing to do with memory.




回答2:


Do you need the first empty bitmap? Without it, you allocate only 3*200 MB instead of 4*200 MB, perhaps this will work:

Dim g As Graphics = Graphics.FromImage("C:\background.png")
g.DrawImage(Image.FromFile("C:\firstlayer.png"), New Point(0, 0))
// and so on

It's strange that overlaying in several steps doesn't work, I think you're not freeing memory correctly in this case. Perhaps it will be better to post the code you're using for this approach.

I also assume that you do need the original images somewhere else or do specifically want to do this using C#/GDI+, as it would be very easy to merge the PNG files using some image editing programs.



来源:https://stackoverflow.com/questions/1239624/overlaying-images-with-gdi

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