delphi 位图到JPEG压缩

nbewdwxp  于 2023-01-13  发布在  其他
关注(0)|答案(1)|浏览(157)

我一直在尝试将位图转换为压缩的JPEG以保存数据库空间,但到目前为止还没有成功。我使用 Delphi 11. 1与FMX。
我的代码如下所示:

var
  NewBitmap: TBitmap;
  CodecParams : TBitmapCodecSaveParams;
  MS1 : TMemoryStream;
  Surf: TBitmapSurface;
  JpgQuality : TBitmapCodecSaveParams;
begin
  ...

  JpgQuality.Quality := 100;

  MS1.Position := 0;
  Surf := TBitmapSurface.create;
  try
    Surf.assign(NewBitmap);
    // use the codec to save Surface to stream
    if not TBitmapCodecManager.SaveToStream(
                       MS1,
                       Surf,
//                     '.jpg', JpgQuality) then     // THIS DOES NOT WORK
                       '.jpg') then                 // THIS DOES WORK BUT NO COMPRESSION (FORMAT MAY NOT EVEN BE JPEG)
      raise EBitmapSavingFailed.Create(
              'Error saving Bitmap to jpg');
  finally
    Surf.Free;
  end;

  ...
end;
unftdfkk

unftdfkk1#

如果选中该功能:

class function SaveToStream(const AStream: TStream; const ABitmap: TBitmapSurface; const AExtension: string;  const ASaveParams: PBitmapCodecSaveParams = nil): Boolean; overload;

可以看到ASaveParamsPBitmapCodecSaveParams的类型:

PBitmapCodecSaveParams = ^TBitmapCodecSaveParams;

正如AmigoJack提到的,您需要使用指针:

var
  NewBitmap: TBitmap;
  MS1 : TMemoryStream;
  Surf: TBitmapSurface;
  JpgQuality : TBitmapCodecSaveParams;
begin
  NewBitmap := TBitmap.CreateFromFile('input.bmp');
  MS1 := TMemoryStream.Create;
  Surf := TBitmapSurface.create;

  try
    MS1.Position := 0;
    Surf.Assign(NewBitmap);
    JpgQuality.Quality := 100;

    if not TBitmapCodecManager.SaveToStream(MS1, Surf, '.jpg', @JpgQuality) then
      raise EBitmapSavingFailed.Create('Error saving Bitmap to jpg');

    MS1.SaveToFile('ouput.jpg');
  finally
    NewBitmap.Free;
    MS1.Free;
    Surf.Free;
  end;
end;

相关问题