Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top