Add a bmp or jpg picture to a canvas in Delphi

Question:

Is it possible for me to programmatically insert a jpg or bmp image onto a canvas?
I'm using canvas in a TBitmap at program time because my application doesn't have a canvas. It is called, creates the drawing according to passed parameters and exits.
Below is a part of my code:

var
  bCan: TBitmap;
begin
  bCan := TBitmap.Create;
  bCan.Width := 800;
  bCan.Height := 500;
  bCan.Canvas.Lock;

  // Desenhos diversos com linhas e retângulos

  bCan.Canvas.Unlock;
end;

Answer:

It depends where the image you want to insert in bCan .

Let's say it's in a directory, you can use the bCan.LoadFromFile command

Take a look at variations of TBitmap LoadFrom... command

Edit:

Take a look, and see if this works for you:

unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls;

type
  TForm2 = class(TForm)
    Panel1: TPanel;
    btnPosicionarImagem: TButton;
    btnCarregarImagem: TButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure btnPosicionarImagemClick(Sender: TObject);
    procedure btnCarregarImagemClick(Sender: TObject);
  private
    Image: TBitmap;
    Canvas: TControlCanvas;

    procedure CarregarImagemBitmap;
    procedure PosicionarPainel;
    procedure CarregarImagemCanvas;
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}




procedure TForm2.FormCreate(Sender: TObject);
begin
  Image  := TBitmap.Create;
  Canvas := TControlCanvas.Create;
end;



procedure TForm2.FormDestroy(Sender: TObject);
begin
  FreeAndNil(Canvas);
  FreeAndNil(Image);
end;



procedure TForm2.CarregarImagemBitmap;
begin
  Image.LoadFromFile('C:\executaveis_01_256x256.bmp');
end;



procedure TForm2.PosicionarPainel;
begin
  Panel1.Width  := Image.Width;
  Panel1.Height := Image.Height;

  Panel1.Left := Random(100);
  Panel1.Top  := Random(100);
end;



procedure TForm2.CarregarImagemCanvas;
begin
  Canvas.Control := Panel1;
  BitBlt(Canvas.Handle, 0, 0, Image.Width, Image.Height, Image.Canvas.Handle, 0, 0, SRCCOPY);
end;



procedure TForm2.btnPosicionarImagemClick(Sender: TObject);
begin
  CarregarImagemBitmap;
  PosicionarPainel;
end;



procedure TForm2.btnCarregarImagemClick(Sender: TObject);
begin
  CarregarImagemCanvas;
end;

end.
Scroll to Top
AllEscort