ImageEn, unit iexBitmaps

TIEBitmap.SaveToStream

TIEBitmap.SaveToStream

Declaration

function SaveToStream(Stream: TStream; FileType: TIOFileType): Boolean;

Description

Saves the image to a stream (in any format supported by the TImageEnIO class).
FileType specifies the image format to save the image. You must specify a valid format (not ioUnknown).
Returns True on success.

Note:
◼TIEBitmap only supports saving of a single frame image. To load and save images containing multiple frames, use TIEMultiBitmap
◼Alternatively, you can use the saving methods of IO
◼For legacy reasons, SaveToStream() is an alias of Write()

Examples

// Output current image to a TImage
bmp := TIEBitmap.Create();
Stream := TMemoryStream.Create();
bmp.LoadFromFile( 'D:\Image.webp' );
bmp.SaveToStream( Stream, ioBMP );
Stream.Position := 0;
Image1.Picture.LoadFromStream( Stream );
Stream.Free();
bmp.Free();


// Example of resizing an image so it does not exceed a maximum size (e.g. for a database blob)

procedure SaveToStreamAtMaxSize(Bitmap: TIEBitmap; Dest: TStream; MaxSizeBytes: Int64; FileType: TIOFileType; JPEGQuality: Integer = 75; ResampleFilter: TResampleFilter = rfFastLinear);
const
  Scale_Reduction_Per_Pass = 0.25; // Reduce size of image by 25% each pass
var
  currScale: Double;
  tempBmp: TIEBitmap;
begin
  currScale := 1.0;
  bmp := TIEBitmap.Create();
  try
    while True do
    begin
      Dest.Size := 0;
      bmp.Assign( Bitmap );

      if ( bmp.Width < 50 ) or ( bmp.Height < 50 ) then
        raise Exception.Create( 'Cannot resample further' );

      bmp.Resample( currScale, ResampleFilter );
      bmp.Params.JPEG_Quality := JPEGQuality;
      bmp.SaveToStream( Dest, FileType );

      if Dest.Size <= MaxSizeBytes then
        EXIT; // SUCCESS

      if Dest.Size > MaxSizeBytes * 4 then
        currScale := currScale * ( 1.0 / Sqrt(Dest.Size / MaxSizeBytes ))   // Image is huge? Reduce more quickly
      else
        currScale := currScale * ( 1.0 - Scale_Reduction_Per_Pass );          // Image is close to size? Fine tuning...
    end;

  finally
    bmp.Free();
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
const
  MAX_SIZE_BYTES = 150 * 1024;
var
  bmp: TIEBitmap;
  ms: TMemoryStream;
begin
  bmp := TIEBitmap.Create();
  ms  := TMemoryStream.Create();
  try
    bmp.LoadFromFile( 'D:\Testing_Multimedia\Big_Big_Pix\570130.jpg' );

    SaveToStreamAtMaxSize( bmp, ms, MAX_SIZE_BYTES, ioJPEG, 80 );

    // Do something with ms, e.g. output to database blob field

    // Test output
    // ms.Position := 0;
    // ImageEnView1.IO.LoadFromStream( ms );

  finally
    ms.Free();
    bmp.Free();
  end;
end;

See Also

◼SaveToFile
◼LoadFromFile
◼Filename
◼IO