How to export CAD files to PNG?
To export CAD files to PNG, follow the steps bellow:
- Add
Graphics
,Dialogs
,CADImage
, andPNGImage
to theuses
section. Add theTOpenPictureDialog
component and name itFOpenPic
.
uses
... Graphics, Dialogs, CADImage, PNGImage;
- Create a procedure to export CAD files to PNG. Declare the local variables:
- Declare
vPicture
and specifyTPicture
as its type. TheTPicture
object works with CAD files whenCADImage
is in theuses
section. - Declare
vBitmap
and specifyTBitmap
as its type. - Declare
vPNGImage
and specifyTPNGImage
as its type.
- Declare
procedure TForm1.ExportToBMPClick(ASender: TObject);
var
vPicture: TPicture;
vBitmap: TBitmap;
vPNGImage: TPNGImage;
- Create instances of the
TPicture
andTBitmap
objects, and then call theLoadFromFile
method as follows. Remember to use thetry...finally
construct to avoid memory leaks.
begin
vPicture := TPicture.Create;
try
if FOpenPic.Execute then
begin
vPicture.LoadFromFile(FOpenPic.FileName);
vBitmap := TBitmap.Create;
- Set the
Width
andHeight
properties of thevBitmap
object. Don't forget to check the value of thevBitmap.Height
property for exceeding the permissible limits.
try
vBitmap.Height := 1;
vBitmap.Width := 1000;
if vPicture.Graphic.Width <> 0 then
vBitmap.Height :=
Round(vBitmap.Width * (vPicture.Graphic.Height /
vPicture.Graphic.Width));
if vBitmap.Height > 4096 then
vBitmap.Height := Round(4096);
vBitmap.Canvas.StretchDraw(Rect(0, 0, vBitmap.Width, vBitmap.Height),
vPicture.Graphic);
We recommend to use such kind of the Height
and Width
properties checks to avoid exceptions.
- Finally, create an instance of the
TPNGImage
object. Use theAssign
andSaveToFile
methods.
vPNGImage := TPNGImage.Create;
try
vPNGImage.Assign(vBitmap);
vPNGImage.SaveToFile(FOpenPic.FileName + '.png');
ShowMessage('File is saved to PNG: ' + FOpenPic.FileName + '.png');
- Don't forget to free the objects.
finally
vPNGImage.Free;
end;
finally
vBitmap.Free;
end;
end;
finally
vPicture.Free;
end;
end;
You have created the procedure to export CAD files to PNG.
The full code listing.
uses
... Graphics, Dialogs, CADImage, PNGImage;
procedure TForm1.ExportToPng(ASender: TObject);
var
vPicture: TPicture;
vBitmap: TBitmap;
vPNGImage: TPNGImage;
begin
vPicture := TPicture.Create;
try
if FOpenPic.Execute then
begin
vPicture.LoadFromFile(FOpenPic.FileName);
vBitmap := TBitmap.Create;
try
vBitmap.Height := 1;
vBitmap.Width := 1000;
if vPicture.Graphic.Width <> 0 then
vBitmap.Height :=
Round(vBitmap.Width * (vPicture.Graphic.Height /
vPicture.Graphic.Width));
if vBitmap.Height > 4096 then
vBitmap.Height := Round(4096);
vBitmap.Canvas.StretchDraw(Rect(0, 0, vBitmap.Width, vBitmap.Height),
vPicture.Graphic);
vPNGImage := TPNGImage.Create;
try
vPNGImage.Assign(vBitmap);
vPNGImage.SaveToFile(FOpenPic.FileName + '.png');
ShowMessage('File is saved to PNG: ' + FOpenPic.FileName + '.png');
finally
vPNGImage.Free;
end;
finally
vBitmap.Free;
end;
end;
finally
vPicture.Free;
end;
end;