[英]How do I save a picture from a open picture dialogue to a file
嗨,我目前正在使用 Delphi 2010。我基本上有一個表單,用戶必須輸入有關自己的信息並上傳圖片。 我的表單上有一個圖像組件。 我做了一些研究,我看到的許多網站都說使用 OpenPictureDialogue 來允許用戶 select 圖像並將其顯示在 Image 組件中。
我的問題是,如何將此圖像保存到計算機上的文件中? 請記住,我將有多個用戶添加他們的圖片,並且稍后我將不得不再次使用圖片,基本上我想稍后使用 LoadFromFile 過程在我的程序中顯示圖片。
我還閱讀了許多網站說要使用 SavePictureDialogue,但這允許用戶 select 他們希望將圖像保存到的文件,我不希望這樣,我希望它保存到只有我可以訪問的文件中。 到目前為止,我有這個,我知道它非常有限。
if opdAcc.Execute then
begin
if opdAcc.FileName <> '' then
begin
imgAccImage.Picture.LoadFromFile(opdAcc.FileName);
end;
end;
我是一名學生,我的知識非常有限,我將不勝感激。 :)
首先,硬盤上沒有只有你可以訪問的地方。 但是您可以創建一個文件夾來存儲您的文件並在那里復制用戶的圖片。 這降低了用戶訪問這些文件的可能性。 存儲此類文件的常用文件夾是AppData
文件夾。 最好在AppData
中創建一個與您的應用程序同名的文件夾並將此類文件存儲在那里。
假設GetPicturesDirectoryPath
function 生成了這樣一個文件夾的地址,並確保這個文件夾已經被創建或將被創建。 下一步是為要存儲的文件生成一個唯一名稱。 請注意,多個用戶可能使用相同名稱的 select 文件。 在這種情況下,復制第二個用戶選擇的圖片后,圖像文件將覆蓋前一個用戶的文件。 如果為每個用戶分配一個唯一的標識符,這個標識符是圖片文件名的最佳選擇。 但您可以使用GetGUIDFileName
function 創建唯一地址。 確保生成的地址與用戶信息的rest一起保存,否則復制的文件與用戶的連接將丟失。 所有這些的實現將如下所示:
uses IOUtils;
function GetAppDataDirectoryPath: string;
begin
...
end;
function GetPicturesDirectoryPath: string;
begin
Result := TPath.Combine(GetAppDataDirectoryPath, 'MyApp');
TDirectory.CreateDirectory(Result);
end;
function GetUniqueFilePath(const Extension: string): string;
begin
Result := TPath.ChangeExtension(
TPath.Combine(GetPicturesDirectoryPath, TPath.GetGUIDFileName),
Extension);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
DestPath: string;
begin
OpenPictureDialog1.Options := OpenPictureDialog1.Options +
[ofFileMustExist]; // make sure that selected file exists
if OpenPictureDialog1.Execute then
begin
DestPath := GetUniqueFilePath(TPath.GetExtension(OpenPictureDialog1.FileName));
TFile.Copy(OpenPictureDialog1.FileName, DestPath);
if TFile.Exists(DestPath) then
Image1.Picture.LoadFromFile(DestPath)
else
ShowMessage('Well, something went wrong!');
end;
end;
閱讀本文以實現GetAppDataDirectoryPath
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.