问题
I'm sure this has been asked before, but I couldn't seem to find it. I use the code below to display an Image from a MS Access database. However, I would like know how to do the following:
-Is it possible to take the procedure below and 'call' it in another form?
Scenario: Three Forms. Three Tables, One Database. I access the tables via a TADOTable component and TADOConnection.
Each form has a button (btnShowImage), to show the picture from the datbase. In order for it to currently work, I need to add the function to the form and then in the the btnShowImage.OnClick, I add the procedure as seen below. This happens on all three forms. My question is: Is there anyway to make it more efficient. Since it seems a little tedious adding this code to all three forms, if it basically does the same (bear in mind, that in the procedure, the table name is different on all three forms). Is there a simpler way of doing this (displaying the image), without having to use all this code on each form?
Thanks for any help!
CODE:
...uses
JPEG, ADODB, DB
function JpegStartsInBlob(PicField: TBlobField): integer;
var
bS: TADOBlobStream;
buffer: Word;
hx: string;
begin
Result := -1;
bS := TADOBlobStream.Create(PicField, bmRead);
try
while (Result = -1) and (bS.Position + 1 < bS.Size) do begin
bS.ReadBuffer(buffer, 1);
hx := IntToHex(buffer, 2);
if hx = 'FF' then begin
bS.ReadBuffer(buffer, 1);
hx := IntToHex(buffer, 2);
if hx = 'D8' then
Result := bS.Position - 2
else if hx = 'FF' then
bS.Position := bS.Position - 1;
end;
end;
finally
bS.Free
end;
end;
procedure Tfrm3.btnShowImageClick(Sender: TObject);
var
bS: TADOBlobStream;
Pic: TJPEGImage;
begin
bS := TADOBlobStream.Create(table1.FieldByName('Photo')
as TBlobField, bmRead);
bS.Seek(JpegStartsInBlob(table1.FieldByName('Photo') as TBlobField),
soFromBeginning);
Pic := TJPEGImage.Create;
Pic.LoadFromStream(bS);
frmOne.Image1.Picture.Graphic := Pic;
Pic.Free;
bS.Free;
end;
Code was found on: http://delphi.about.com/od/database/l/aa030601d.htm
回答1:
What I would do if I had code that had to be called from a button on 3 different forms, which was almost the same everywhere except for a few specific differences from the context of each individual form, is take the code, put it in a unit, and turn the differences into parameters. For example:
procedure LoadJPEGImage(field: TBlobField; image: TImage);
var
bS : TADOBlobStream;
Pic : TJPEGImage;
begin
bS := TADOBlobStream.Create(field, bmRead);
Pic := TJPEGImage.Create;
try
bS.Seek(JpegStartsInBlob(field), soFromBeginning);
Pic.LoadFromStream(bS);
image.Picture.Graphic := Pic;
finally
Pic.Free;
bS.Free;
end;
end;
Now the code doesn't care about the form or any of its details; it just needs a TBlobField to read from and a TImage to draw the picture to, and you can use it on as many forms as you want.
来源:https://stackoverflow.com/questions/11569398/call-procedure-on-another-form