简体   繁体   中英

Delphi> Can I store a bitmap's data in my unit (not the dfm)?

I have a class declared in a unit, and it needs to work with a specific bitmap. It is declared in the DFM of my test unit like this:

  object ImgTop: TImage
    Left = 208
    Top = 568
    Width = 777
    Height = 41
    Picture.Data = {
      0A544A504547496D616765A1CF0000FFD8FFE000104A46494600010101025802
      [truncated]
      };

But in my final unit I won't be having a dfm. So is there a way I can declare it in my unit?

===

Thanks, I seem to have it working now, pitty about the size limitations on bitmaps :( Here's what I did:

In my folder are these files:

imgleft.bmp
imgtop.bmp

This is my resource file called ScanOCRres.rc:

1 RT_BITMAP "imgtop.bmp"
2 RT_BITMAP "imgleft.bmp"

I have set it to automatically execute with C:\\Program Files\\Borland\\Delphi 7\\bin\\brcc32.exe

It generated the file

ScanOCRres.RES

In my unit I have implementation

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

And here's my code:

var
  abmp : TBitmap;
begin
  abmp := TBitmap.create;
  abmp.LoadFromResourceID(SysInit.HInstance, 1);
  abmp.free;
end;

I get this error message on the LoadFromResourceID line:

Project Project1.exe raised exception class EAccessViolation with message 'Access violation at address 0040A2C8 in module 'Project1.exe'. Read of address 00000001 '

You could put it in your code, but it wouldn't be very convenient to work with. Declare an array of bytes and define each byte of your image. Good luck editing it. To load it, I'd wrap the byte array into a TMemoryStream and then use LoadFromStream .

A better way is to store the image in a resource . Write a resource script file like this:

1 RT_BITMAP "foo.bmp"

Add that .rc file to your Delphi project, and it will automatically be linked to your program. At run time, load the image with TBitmap.LoadFromResourceId :

var
  b: TBitmap;
begin
  b := TBitmap.Create;
  b.LoadFromResourceId(SysInit.HInstance, 1);

I made this. It's crude but it works. Converts component's picture to picture.data as a string.

 Procedure ImgToText(Com : TComponent; var str : AnsiString); var i,c : integer; s : tmemorystream; b : byte; t : array[0..3] of char; ch : char; begin s := tmemorystream.Create; s.WriteComponent(com); s.Position := 0; c := 0; repeat s.Read(ch,1); if ch = '.' then begin s.Read(t,4); if t = 'Data' then c := s.Position+5; end; until c <> 0; s.Position := c; str := ''; i := c; c := 0; repeat s.ReadBuffer(b,1); str := str+inttohex(b,2); c := c+2; if c >= 64 then begin str := str+#13+#10; c := 0; end; i := i+1; until i = s.Size-2; s.Free; end; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM