2007. február 25., vasárnap
Create a thumbnail from a JPEG image
Problem/Question/Abstract:
Once I was trying to resize a jpeg image and made some Internet search. Believe or not, I couldn't find clear answers to my question, but it's very easy to do.
Answer:
The code below will reduce width and height of a chosen .jpg image.
Go to "File / New / Console Application" and paste this code. Set the SizePct (a const on the code below, but can be a variable on your program) to fit your needs. If you want a new image with 30% of the original width and height set this to 30.
All I do is load the JPEG on a TJPEGImage, create a bitmap and .StretchDraw the JPEG on the bitmap. Then I copy the bitmap to a TJPEGImage using the .Assign method, and, finally, save it.
program Project1;
{$APPTYPE CONSOLE}
uses
Classes, Windows, SysUtils, Dialogs, JPEG, Graphics;
const
SizePct: integer = 50; { The new image will have 50% of the original }
var
OpenDlg: TOpenDialog;
SaveDlg: TSaveDialog;
oJPG: TJPEGImage;
oBmp: TBitmap;
begin
OpenDlg := TOpenDialog.Create(nil);
SaveDlg := TSaveDialog.Create(nil);
if (OpenDlg.Execute) then
begin
try
begin
oJPG := TJPEGImage.Create;
oJPG.LoadFromFile(OpenDlg.FileName);
end
except
MessageBox(
0,
PChar('Error while trying to open ' +
OpenDlg.FileName +
'.'),
PChar('Error'),
MB_OK or MB_ICONERROR
);
exit;
end;
oBmp := TBitmap.Create;
oBmp.Width := Round(oJPG.Width * SizePct / 100);
oBmp.Height := Round(oJPG.Height * SizePct / 100);
oBmp.Canvas.StretchDraw(
Rect(0, 0, oBmp.Width - 1, oBmp.Height - 1),
oJPG
);
oJPG.Assign(oBmp);
oJPG.Compress;
if (SaveDlg.Execute) then
begin
oJPG.SaveToFile(SaveDlg.FileName);
end;
oBmp.Free;
oJPG.Free;
end;
OpenDlg.Free;
SaveDlg.Free;
end.
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése