tags:

views:

106

answers:

2

I have an application that prints text and images to pages on a printer. At the footer, we output an image, which is cached by loading it once, and stored in a TBitmap. In the print routine, it creates a new TBitmap, then calls a function which assigns the cached bitmap. It then ends up calling Canvas.StretchDraw on that bitmap.

Function GetFooterGraphic(Var xBitmap : TBitmap) : boolean;
begin
  // load cache here
  if assigned(g_xFooterBitmap) then
  begin
    xBitmap.Assign(g_xFooterBitmap);
    result := true;
  end;
end

// Get bitmap, then:
xCanvas.StretchDraw(xDrawRect, xBitmap);

The problem is that the bitmap is failing to work after a certain number of pages. I can only imagine that this is a driver problem, but it happens on most printers at different times. I can fix it by reloading the bitmap each time, but I'd rather keep the cache.

Having looked at the VCL, the xBitmap.Assign actually just adds a reference to the stored item. What I want to do is take a complete copy, the most efficient way. Which comes to the question:
How can I make the TBitmap content completely independent of any other reference?

I'd like to keep the cached TBitmap content completely independent, and return a complete (deep) copy, so that the printing does not affect the cached version, and thus hopefully fix this issue.

Delphi 2007 if relevant.

A: 

I'd use SaveToStream and LoadToStream, probably with a TMemoryStream.

Roddy
That was what I was looking at doing. Certainly would have worked.
mj2008
+3  A: 

I cannot test it here because I'm not able to reproduce the problem, but perhaps a call to FreeImage right after the Assign may help.

Uwe Raabe
This solves it. I looked at the source to TBitmap, and never actually looked at this. "FreeImage" is not what I'd expect it to be! It is "free as in spirit", not "free as in memory".
mj2008
When having trouble with printing + bitmaps, I've learned to call `FreeMemoryContexts` or `bmp.Handle`. Pure cargo cult programming but it seems to work a lot of the time.
Ulrich Gerhardt