Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem converting bmp to jpg using TJpegImage Component

Tags:

delphi

I have a bmp file and am trying to convert it to jpeg format. The jpeg created using the following code loses a lot of clarity. I have tried tweaking many settings to no avail.

Does anyone have a function which will convert a bmp file to a jpeg?

var
  Bmp: TBitmap;
  Jpg: TJPEGImage;
begin
  Bmp := TBitmap.Create;
  Jpg := TJPEGImage.Create;
  try
    Bmp.LoadFromFile(BmpFileName);
    Jpg.Assign(Bmp);
    jpg.PixelFormat    :=jf24bit;  // or jf8bit
    Jpg.CompressionQuality := 100;
    Jpg.ProgressiveDisplay := False;
    Jpg.ProgressiveEncoding := False;

    Jpg.SaveToFile(JpgFileName);
  finally
    Jpg.Free;
    Bmp.Free;
  end;
end;

Update II A lot of people have responded that jpeg is not the graphic type to use in this case. Understood. Not to beat a dead horse, but I have been able to use other programs (i.e. Photoshop) and convert this to a nice looking jpeg. And the tool I am using to create the chart (fusioncharts) is able to export it to a nice looking jpeg too (see below). What is the difference?

like image 467
M Schenkel Avatar asked Jun 23 '10 13:06

M Schenkel


1 Answers

If you want to loose as little quality as possible, then you should compress as little as possible, i.e. set CompressionQuality := 100.

Update

The JPG image format is designed to be used with photographs and similar raster pictures. JPG employs destructive compression to reduce the file size. However, the visual effect of this compression is negligible for large quality values (> ~80) because photographs do not contain large areas of the same colour, very regular shapes, etc.

The JPG format should never be used for anything other than photographic pictures. For instance, diagrams, screenshots, etc, that do contain large areas of the exact same colour, very regular shapes, etc, will display clear artefacts when JPG compressed. For this type of raster images, use PNG. PNG is also a compressed format (a very, very good format too!), but the compression is non-destructive.

So please do not use JPG for your diagram! Use PNG!

like image 131
Andreas Rejbrand Avatar answered Oct 06 '22 01:10

Andreas Rejbrand