Title: Change JPEG File Size vs Quality (CompressionQuality)
Question: Whilst doing some web page work, we needed to optimize some of our JPG file sizes for web load times. You can often reduce the file size (not the display size) of a JPG file considerably without significantly decreasing the image quality. Searching the web for a tool produced various shareware and purchasable tools that was not what I wanted. Looking to Delphi I found that TJpegImage was more than capable of saving a JPG with different compression qualities. I wrote my own tool to vary the Size vs Quality ratios of JPG files.
Without boring you with the full application code, which obviously allows viewing the original against a modified JPG with a compression ratio slider bar, I will demonstrate how to convert an input JPG file to an outfile file with a different compression ratio by a simple Delphi procedure.
procedure SetJPGCompression(ACompression : integer; const AInFile : string; const AOutFile : string);
Parameters
-----------------
ACompression : Ratio to use for compression 1..100 (Most of the JPG files I use seem to have a default of 75, setting them higher than 75 actually INCREASES file size without increasing quality. Settings of 40 gave me acceptable quality at nearly HALF the file size, play around with this value on a slider bar)
AInFile : Filename of JPG file to convert.
AOutFile : Filename of converted output file.
Answer:
uses JPEG;
// ====================================================
// Set the compression quality of a JPEG image
// This will alter the quality vs size ratio
// ====================================================
procedure SetJPGCompression(ACompression : integer; const AInFile : string;
const AOutFile : string);
var iCompression : integer;
oJPG : TJPegImage;
oBMP : TBitMap;
begin
// Force Compression to range 1..100
iCompression := abs(ACompression);
if iCompression = 0 then iCompression := 1;
if iCompression 100 then iCompression := 100;
// Create Jpeg and Bmp work classes
oJPG := TJPegImage.Create;
oJPG.LoadFromFile(AInFile);
oBMP := TBitMap.Create;
oBMP.Assign(oJPG);
// Do the Compression and Save New File
oJPG.CompressionQuality := iCompression;
oJPG.Compress;
oJPG.SaveToFile(AOutFile);
// Clean Up
oJPG.Free;
oBMP.Free;
end;