Giacomo King Patermo
Giacomo King Patermo

Reputation: 849

Load bitmap from resource file to image

how do I load an image bmp from resource file and load it into image1.Picture? I tried this:

{$R resource.res}
procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
 BitMap1 : TBitMap;
begin
  BitMap1 := TBitMap.Create;
  try
    BitMap1.LoadFromResourceName(HInstance,'down');
    Image1.Picture(BitMap1);
  finally
    BitMap1.Free;
  end;
end;

but does't work. Thanks!


I created a file. rc:

DOWN BMP DOWN.BMP 

and I compiled with brcc32.exe:

brcc32.exe resource.rc

I implemented the resource:

{$R resource.res}

but can not find the file bmp.


It does not work, always an error, however I found another code:

procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
   Image1.Picture.Bitmap.Handle := LoadBitmap(hInstance, 'DOWN');
end;

But when I click on the image disappears, why? Thanks

This is the code:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, XPMan, ExtCtrls;

type
  TForm1 = class(TForm)
    XPManifest1: TXPManifest;
    Image1: TImage;
    procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
{$R RESOURCE.RES}

procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
   Image1.Picture.Bitmap.Handle := LoadBitmap(hInstance,'DOWN');
end;

end.

Upvotes: 1

Views: 23603

Answers (2)

ShirleyCC
ShirleyCC

Reputation: 805

In Delphi 10 or later you can to create the resource go up to Project Menu Project > Resources and Images

http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Resources_and_Images

Upvotes: 0

Ken White
Ken White

Reputation: 125749

You have to create the resource correctly in the first place. Example (generic Delphi, since you didn't specify a version) below.

File: Resource.rc (terrible name, BTW, and a terrible resource name)

DOWN BITMAP DOWN.BMP

Then include the file in the code for the compiler to process:

{$R resource.res resource.rc}

procedure TForm1.Image1MouseDown(Sender: TObject; Button: TMouseButton; 
  Shift: TShiftState; X, Y: Integer);
var
 BitMap1 : TBitMap;
begin
  BitMap1 := TBitMap.Create;
  try
    BitMap1.LoadFromResourceName(HInstance,'DOWN');
    Image1.Picture.Assign(Bitmap1);;
  finally
    BitMap1.Free;
  end;
end;

If your version of Delphi doesn't support the above {$R } directive, just remove the resource.rc part, and compile the resource from a command prompt in your project folder first:

brcc32 resource.rc

Upvotes: 7

Related Questions