Cannot compress JPEG image and display it on screen.

I am trying to load an image into imgQInput (this is TImage), assign it to TJpegImage, compress it (compression ratio 5) and show it in imgQOutput (another TImage). But that will not work. The image in imgQOutput matches the original image. It should look VERY pixelated due to the compression ratio! However, compression works because when I save a JPEG to disk, it is really small.

  JPG:= TJPEGImage.Create;
   TRY
     JPG.CompressionQuality:= trkQuality.Position;
     JPG.Assign(imgQInput.Picture.Graphic);
     CompressJpeg(JPG);
     imgQOutput.Picture.Assign(JPG);          <--------- something wrong here. the shown image is not the compressed image but the original one
   FINALLY
     FreeAndNil(JPG);
   END;


function CompressJpeg(OutJPG: TJPEGImage): Integer;
VAR tmpQStream: TMemoryStream;
begin
 tmpQStream:= TMemoryStream.Create;
 TRY
   OutJPG.Compress;
   OutJPG.SaveToStream(tmpQStream);
   OutJPG.SaveToFile('c:\CompTest.jpg');       <--------------- this works
   Result:= tmpQStream.Size;
 FINALLY
   FreeAndNil(tmpQStream);
 END;
end;
+5
source share
2 answers

You did not use compressed JPG at all.

Change CompressJpegas follows:

function CompressJpeg(OutJPG: TJPEGImage): Integer;
VAR tmpQStream: TMemoryStream;
begin
 tmpQStream:= TMemoryStream.Create;
 TRY
   OutJPG.Compress;
   OutJPG.SaveToStream(tmpQStream);
   OutJPG.SaveToFile('c:\CompTest.jpg');    // You can remove this line.
   tmpQStream.Position := 0;                //
   OutJPG.LoadFromStream(tmpQStream);       // Reload the jpeg stream to OutJPG
   Result:= tmpQStream.Size;
 FINALLY
   FreeAndNil(tmpQStream);
 END;
end;
+6
source

Here is a competing answer for you, with less data juggling (remember, images can be large!)

type
  TJPEGExposed = class(TJPEGImage);     // unfortunately, local class declarations are not allowed

procedure TForm1.FormClick(Sender: TObject);
var
  JPEGImage: TJPEGImage;
const
  jqCrappy = 1;
begin
  Image1.Picture.Bitmap.LoadFromFile(GetDeskWallpaper);

  Image2.Picture.Graphic := TJPEGImage.Create;
  JPEGImage := Image2.Picture.Graphic as TJPEGImage;    // a reference
  JPEGImage.Assign(Image1.Picture.Bitmap);
  JPEGImage.CompressionQuality := jqCrappy;    // intentionally
  JPEGImage.Compress;
  TJPEGExposed(JPEGImage).FreeBitmap;    { confer: TBitmap.Dormant }
end;

TJPEGImage.FreeBitmap DIB, TJPEGImage. .Compress 'ed JPEG TImage .

+3

All Articles