2010-10-05 92 views
4

您好,我目前工作的一個程序,我想添加一個按鈕將允許用戶加載從他的電腦圖片插入圖片加載圖片到圖像德爾福

procedure TForm1.btnLoadPicClick(Sender: TObject); 
begin 
img1.Picture.LoadFromFile('test.1'); 
img1.Stretch := True ; 

我用這代碼,但它限制了人,只能夠使用特定的畫面,我想他選擇一個從他的電腦謝謝:)

回答

12

你需要顯示一個打開的對話框:

procedure TForm1.Button1Click(Sender: TObject); 
begin 
    with TOpenDialog.Create(self) do 
    try 
     Caption := 'Open Image'; 
     Options := [ofPathMustExist, ofFileMustExist]; 
     if Execute then 
     Image1.Picture.LoadFromFile(FileName); 
    finally 
     Free; 
    end; 
end; 
+0

非常感謝:)很好地工作 – Noobdelphi 2010-10-05 15:57:50

+2

+1 - 儘管'與'。 – 2010-10-05 16:18:34

+4

對於nitpicking,在'Create/try /.../ finally/Free/end'這樣的構造中,最好省略所有者(Self)並使用'Create(nil)'。它可以避免在整個應用程序中發送大量不必要的通知消息。 – 2010-10-05 17:11:17

1

首先將Timage和OpenPictureDialog放置在窗體上,然後在您的使用子句中添加jpeg。然後點擊事件btnLoadPic把代碼設置爲

procedure TForm1.btnLoadPicClick(Sender:TObject);

開始

If not OpenPictureDialog1.Execute Then 
     Exit; 
    Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName); 
    //If not (Image1.Picture.Graphic is TJPEGImage) Then 

    //raise Exception.Create('File not JPEG image'); 

結束;

如果您只想要JPEG圖像,請取消對註釋行的註釋。在對象檢查器中,您可以將Timage屬性Stretch設置爲True。