无法压缩JPEG图像并在屏幕上显示

时间:2012-02-26 20:46:50

标签: delphi

我尝试在imgQInput(这是一个TImage)中加载图像,将其分配给TJpegImage,压缩它(压缩因子5)并在imgQOutput(另一个TImage)中显示它。但它不起作用。 imgQOutput中的图像与原始图像相同。由于压缩因素,它应该看起来非常像素化!然而,压缩工作正常,因为当我将JPEG保存到磁盘时,它确实很小。

  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;

2 个答案:

答案 0 :(得分:6)

您根本没有使用过压缩的JPG。

更改CompressJpeg如下:

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;

答案 1 :(得分:3)

这是一个竞争性的答案,数据量较少(请记住,图像可能很大!)

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处理TJPEGImage实例中包含的volatile DIB。在图示的情况下,这导致类解码最近.Compress'ed JPEG以响应TImage重新绘制。