Search code examples
delphisizejpegreduce

How to reduce the size of JPG file?


Few days ago I asked this question and got the answer: How to add a picture frame and insert the text in the image?

Now, when I save content from TPanel (1x shape, 1x TImage, 2x TLabel) as JPG file,
size of that JPG file is increased from 20kb, wich is size of picture in TImage, to 620kb.

Dimensions are almost same. Original JPG file 320x320, new JPG picture 361x440.

So, how to reduce that size?

This is answer for first question, from @iPath, so that is how new JPG file is created:

procedure TForm1.SavePanelAsImage;
var
 img: TBitmap;
begin
 img := TBitmap.Create;
 try
  img.Width := fpPanel.Width;
  img.Height := fpPanel.Height;
  fpPanel.PaintTo(img.Canvas, 0, 0);
  img.SaveToFile(fpFileName);
 finally
  img.Free;
end;
end;

Solution

  • What you have saved is not a JPEG image. You have saved a Windows bitmap. That has no compression at all. It happens to have the .jpg extension, but that doesn't make the file itself be a JPEG.

    You need to use TJPEGImage to save the file. Control the compression by using the CompressionQuality property. Once you have your image in a bitmap, transfer it to a JPEG

    uses
      jpeg;
    
    procedure TForm1.SavePanelAsImage;
    var
      img: TBitmap;
      JpegImage: TJPEGImage;
    begin
      img := TBitmap.Create;
      try
        img.Width := fpPanel.Width;
        img.Height := fpPanel.Height;
        fpPanel.PaintTo(img.Canvas, 0, 0);
        JpegImage := TJPEGImage.Create;
        try
          JpegImage.CompressionQuality := ...;//you decide the value
          JpegImage.Assign(img);
          JpegImage.SaveToFile(fpFileName);
        finally
          JpegImage.Free;
        end;
      finally
        img.Free;
      end;
    end;