BennieC
BennieC

Reputation: 23

Bitmap to JPEG Compression

I have been trying to convert bitmaps to compressed jpegs to save space in a database, but so far with no success. I use Delphi 11.1 with FMX.

My code looks as follows:

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;

Upvotes: 0

Views: 543

Answers (1)

Haifisch
Haifisch

Reputation: 909

If you check the function :

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

You can see that ASaveParams is type of PBitmapCodecSaveParams :

PBitmapCodecSaveParams = ^TBitmapCodecSaveParams;

As mentionned by AmigoJack you need to use a pointer :

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;

Upvotes: 2

Related Questions