Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

resample a jpeg?

Status
Not open for further replies.

AP81

Programmer
Apr 11, 2003
740
AU
Hi,

I've written some code to resampe a JPEG if it is bigger than 640x480. My code seems a little hackish, so I'd like to improve it. Any suggestions?

Code:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, JPEG;

type
  TForm1 = class(TForm)
    Button2: TButton;
    procedure Button2Click(Sender: TObject);
    procedure ResampleJPEG(jpg : TJPEGImage; sNewFileName : String);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button2Click(Sender: TObject);
var
  jpg : TJPEGImage;
begin
  try   {try-finally}
    try {try-except}
      jpg := TJpegImage.Create;
      jpg.LoadFromFile('test2.jpg');
      if ((jpg.Width > 640) OR (jpg.Height > 480)) then ResampleJPEG(jpg,'newtest2.jpg');
    except
      ShowMessage('Not a valid JPEG image!');
    end;  {end try-except}
  finally
    jpg.Free;
  end;   {end try-finally}
end;

procedure TForm1.ResampleJPEG(jpg : TJPEGImage; sNewFileName : String);
var
  bmp, newbmp :  TBitmap;
  stretchrect : trect;
begin
  try   {try-finally}
    try {try-except}
      //create a rectangle to resize a bitmap or JPEG into
      stretchrect.Left := 0;     //left corner of rectangle
      stretchrect.Top := 0;      //top of rectangle
      stretchrect.Right := 640;  //width
      stretchrect.Bottom := 480; //height
      //create bitmaps
      bmp     := TBitmap.Create;
      newbmp  := TBitmap.Create;
      //set the size of the new bitmap
      newbmp.Width := stretchrect.Right;
      newbmp.Height := stretchrect.Bottom;
      //assign bitmap
      bmp.Assign(jpg);
      //resample bitmap
      newbmp.Canvas.StretchDraw(stretchrect,bmp);     //resample
      //save jpeg
      jpg.Assign(newbmp);
      jpg.CompressionQuality := 90;
      jpg.SaveToFile(sNewFileName);
      ShowMessage('JPEG has been resampled successfully');
    except
      ShowMessage('Error while resampling JPEG!');
    end;    {end try-except}
  finally
    bmp.FreeImage;
    bmp.Free;
  end;     {end try-finally}
end;

end.




------------------------------------
There's no place like 127.0.0.1
------------------------------------
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top