Mega Code Archive

 
Categories / Delphi / Files
 

Save TWinControl components image to file

Title: Save TWinControl component's image to file Question: This code shows an easy way to capture a component's image and convert BMP 2 JPEG. It also has ability to capture a full screen shot, use GetDC(0) instead of GetDC(AControl.Handle) and set canvas's rect as screen. But that is not the point. Answer: uses Jpeg; procedure SaveControlImageToFile(AControl : TWinControl; AFileName : string; UseJpegFormat : boolean = true); var Canvas : TCanvas; Bmp : TBitmap; Jpg : TJpegImage; begin try Canvas := TCanvas.Create; Canvas.Handle := GetDc(AControl.Handle); Bmp := TBitmap.Create; Bmp.Width := AControl.Width; Bmp.Height := AControl.Height; bmp.PixelFormat :=pf24bit; Bmp.Canvas.CopyRect(Canvas.ClipRect, Canvas, Canvas.ClipRect); if UseJpegFormat then begin Jpg := TJpegImage.Create; jpg.PixelFormat := jf24bit; Jpg.Assign(Bmp); Jpg.SaveToFile(ChangeFileExt(AFileName,'.jpg')); end Else Bmp.SaveToFile(ChangeFileExt(AFileName,'.bmp')); finally ReleaseDC(AControl.Handle, Canvas.Handle); FreeAndNil(Bmp); if UseJpegFormat then FreeAndNil(Jpg); FreeAndNil(Canvas); end; end;