CreateFromStream (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates how to create a TBitmap using the CreateFromStream constructor.

To build and test this example, create a Multi-Device Application, then add the next objects to the form:

Add the following code to the OnClick event handler of the button.

Code

procedure TForm1.Button1Click(Sender: TObject);
var
  // The stream to create the bitmap from
  Stream: TStream;
  // The bitmap to be created
  Bitmap: TBitmap;
begin
  if OpenDialog1.Execute then
  begin
    // Create the stream for the bitmap that will be loaded
    Stream := TFileStream.Create(OpenDialog1.Filename, fmOpenRead or
      fmShareDenyNone);
    try
      // Create the new bitmap
      Bitmap := TBitmap.CreateFromStream(Stream);
      try
        if Bitmap.IsEmpty then
          // Display a message when the bitmap cannot be loaded
          TDialogServiceAsync.MessageDialog(
            Format('Can not load image: %s', [OpenDialog1.Filename]),
            TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOk], TMsgDlgBtn.mbOk, 0)
        else
        begin
          // Copy the new bitmap to the image object, to be displayed
          Image1.Bitmap := Bitmap;
          Label1.Text := Format('Loaded from: %s', [OpenDialog1.Filename]);
        end;
      finally
        Bitmap.Free;
      end;
    finally
      Stream.Free;
    end;
  end;
end;

Uses

See Also