Tuesday, December 17, 2024

Saving a form's image as jpg file

Yesterday, when writing about a new feature in the Blog Manager program, I wrote1 "I thought that it would be helpful if I could save the graph as an image". I found some old tech tips that helped me write the code; some of this was very low level with reference to device contexts and similar.

Still reading "Smarter than you think"2, where Clive ponders AI and Jeopardy, I got the idea of asking AI program co-pilot to write a program in Delphi to save a form's image as jpg. Well, it did, and the procedure is remarkably similar to what I pieced together, although without all the low level device contexts.

procedure TForm1.SaveFormAsJPG(const FileName: string); var Bitmap: TBitmap; JpegImage: TJpegImage; begin Bitmap:= TBitmap.Create; JpegImage:= TJpegImage.Create; try // Capture the form's image Bitmap.Width:= Self.ClientWidth; Bitmap.Height:= Self.ClientHeight; Self.PaintTo (Bitmap.Canvas.Handle, 0, 0); // Convert the bitmap to JPG JpegImage.Assign(Bitmap); // Save the JPG to a file JpegImage.SaveToFile(FileName); finally Bitmap.Free; JpegImage.Free; end; end;

I don't want the entire form to be saved, only the graph, so it may be that the critical PaintTo procedure will not be available for a TChart that is apparently based on TPanel. I'll have to check this*. As far as I can see, the PaintTo procedure hides all the device context code.

* Indeed, CoPilot's code works, even when 'self' is replaced by 'chart1'. Well done!

Internal links
[1] 1874
[2] 1873



This day in history:

Blog #
Date
TitleTags
2117/12/2005
The Brief and The BookTV series, Van der Graaf Generator
78617/12/2014
Seasonal greetingsJewish holidays
156717/12/2022
Doctoral thesis extension grantedDBA

No comments: