For Newbie

Tuesday, 15 November 2011

Saving Graphic Files JPEG With Different Quality by Delphi



Example of storing graphics into JPEG files which is different from the original picture quality by using a TImage.

Declaration procedure:
SaveJPGWQ procedure (img: TImage; q: TJPEGQualityRange; FDest: TFileName);
var
   iJPG: TJPEGImage;
   iBMP: TBitmap;
begin
   iJPG: = TJPEGImage.Create;
   try
     if img.Picture.Graphic <> nil then
     begin
       if img.Picture.Graphic is TBitmap then iJPG.Assign (img.Picture.Graphic)
       else
       begin
         iBMP: = TBitmap.Create;
         try
           iBMP.Assign (img.Picture.Graphic);
           iJPG.Assign (iBMP);
         finally
           iBMP.Free;
         end;
       end;
       with iJPG do
       begin
         CompressionQuality: = q;
         Compress;
         SaveToFile (FDest);
       end;
     end;
   finally
     iJPG.Free;
   end;
end;

To set the image quality, use the parameter q. Its scope is [1 .. 100] with the assumption that the greater value is given then the image quality of the original will remain intact and vice versa.

*) Add the clause uses the JPEG unit.

Example of implementation:
procedure TForm1.Button1Click (Sender: TObject);
begin
   SaveJPGWQ (image1, 80, 'C: \ JPG1.JPG');
end;

Example implementations # 2 (using TTrackBar and TSaveDialog):
procedure TForm1.Button2Click (Sender: TObject);
begin
   if Image1.Picture.Graphic <> nil then
   begin
     if SaveDialog1.Execute then
     begin
       SaveJPGWQ (image1, TrackBar1.Position, SaveDialog1.FileName);
     end;
   end;
end;

Share on Facebook
Share on Twitter
Share on Google+

Related : Saving Graphic Files JPEG With Different Quality by Delphi