ImageEn, unit iexBitmaps

TIEBitmap.SaveToStream

TIEBitmap.SaveToStream


Declaration

function SaveToStream(Stream: TStream; ImageFormat: TIOFileType): boolean;


Description

Saves the image to a stream (in any format supported by the TImageEnIO class).
You must specify the ImageFormat.
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; Format: 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;
  tempBmp := TIEBitmap.Create();
  try
    While True do
    begin
      Dest.Size := 0;
      tempBmp.Assign( Bitmap );

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

      tempBmp.Resample( currScale, ResampleFilter );
      tempBmp.Params.JPEG_Quality := JPEGQuality;
      tempBmp.SaveToStream( Dest, Format );

      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
    tempBmp.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