How do I properly configure the Timage bitmap assignment?
I do the following to resize Timage plot and save it as jpg. image is saved blank.
this is how i assign Timage
begin
with TOpenDialog.Create(self) do
try
Caption := 'Open Image';
Options := [ofPathMustExist, ofFileMustExist];
Filter := 'JPEG Image File (*.jpg)|*.jpg|JPEG Image File (*.jpeg)|*.jpeg|Bitmaps (*.bmp)|*.bmp';
if Execute then
image1.Picture.LoadFromFile(FileName);
finally
Free;
end;
end;
and this is how I resize the time and assign it to jpg.
with Image2.Canvas do begin
Lock;
try
try
Image2.Picture.Graphic.Width := 50;
Image2.Picture.Graphic.Height := 50;
FillRect(ClipRect);
StretchDraw(rect(0, 0, 50, 50), image1.Picture.Bitmap);
except
on E: Exception do
//log
end;
finally
Unlock;
end;
end;
Jpg := TJPEGImage.Create;
try
Jpg.Performance := jpBestSpeed;
Jpg.ProgressiveEncoding := True;
Jpg.ProgressiveDisplay := True;
Jpg.Assign(image2.Picture.Bitmap);
Jpg.CompressionQuality := 90;
Jpg.Compress;
jpg.SaveToFile('screena.jpg');
finally
Jpg.Free;
end;
The saved jpg becomes empty, what am I doing wrong? all I have to do is load the image from disk into Timage, then adjust the width and height and re-assign it to jpg
source to share
The reason your image is blank is because you are using a property Picture.Bitmap
when painting Image1
to canvas Image2
:
StretchDraw(rect(0, 0, 50, 50), image1.Picture.Bitmap);
If you have NOT loaded the file .bmp
into Image1
, accessing the property Bitmap
will destroy the current image and replace it with an empty image. This is the documented behavior :
Use
Bitmap
to reference an image object when it contains a bitmap . IfBitmap
referenced when the image contains metafile or icon graphicsBitmap
, the graphic will not be converted ( Types of Graphics ). Instead, the original image content is discarded and a new, empty raster map is returned .
The method TCanvas.StretchDraw()
accepts any object TGraphic
in its third parameter. You must pass a property Picture.Graphic
instead of a property Picture.Bitmap
:
StretchDraw(rect(0, 0, 50, 50), image1.Picture.Graphic);
Side note: When assigning a property, TOpenDialog.Filter
consider using a VCL function GraphicFilter()
in a moduleGraphics
Returns a file filter that is compatible with the
Filter
Open or Save dialog property .Call
GraphicFilter
to get the value forFilter
the Open, Open Picture, Save Picture, or Save dialog property . The parameterGraphicClass
may indicate one of the following:TBitmap
,TGraphic
,TIcon
,TMetafile
or user-defined descendantTGraphic
.
For example:
Filter := GraphicFilter(TGraphic);
If you're going to fill in Filter
manually, then at least you don't have separate entries for the different JPEG extensions. Group them together into one entry, for example:
Filter := 'JPEG Images (*.jpg, *.jpeg)|*.JPG;*.JPEG|Bitmap Images (*.bmp)|*.BMP';
source to share