Out of memory while printing Pictures using PrintDocument

funch

New member
Joined
Jun 7, 2007
Messages
4
Programming Experience
10+
Hi,

I am trying to print a number of graphics using the PrintDocument function and during the creation of the print-page I get an Out of Memory exception.

My machine has 8GB of memory and never shows it running low on memory at any point (it's a Quad Core 2.66)

Code:

An array of pictures (paths to pictures) are loaded into ALPix (arraylist)

Private Sub Print_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles Print.PrintPage
Dim PicRec As Rectangle = New Rectangle(x(1), y, 100, 100)
Dim prFont As New Font("Verdana", 8, FontStyle.Bold)

While (CurPix < PixNo) Or (y < 900)

' Draw Picture on Page
PicRec = New Rectangle(x(xLoc), y, 100, 100)
e.Graphics.DrawImage(Image.FromFile(ALPix(CurPix)), PicRec)

' Draw Picture Title on Page
prFont = New Font("Verdana", 8, FontStyle.Bold)
e.Graphics.DrawString(SplitPath(ALPix(CurPix), 3), prFont, Brushes.Black, x(xLoc), y + 100)

CurPix += 1 ' Next picture
xLoc += 1 ' Next x Location
If xLoc = 7 Then
xLoc = 1
y += Spacing ' Jump down on the page
End If
End While
End Sub

The pictures loaded are between 10KB and 30KB in size and it 'run out' at the 47th picture and it seems that those add up to about 1MB altogether.

Is there a way to clear the memory usage after each picture or am I doing something else wrong? I don't really care how they are printed if there's a better way.

Thanks
~j
 
Two unresolved issues with your code in relation to the Image.FromFile method documentation remarks:
The file remains locked until the Image is disposed.

If the file does not have a valid image format or if GDI+ does not support the pixel format of the file, this method throws an OutOfMemoryException exception.
To solve the first you should declare a variable of type Image and assign it the Image.FromFile result, when finished with each file you call .Dispose to free the file, else it could take some time before GC cleans up for you.

The second remark is probably the reason why you get OutOfMemoryException, to detect this you have to TryCatch the Image.FromFile call. If the reason is this call and the problem is the pixel format the code will continue. I doubt there are other "real" memory issues.
 
Hi John,

I am such a dumba$$... Yes the picture was in fact 'broken' although image viewers recognized it...

Sorry for wasting your time, thank you for getting me on the right track!

~j
 
Back
Top