Delphi中如何从URL获取图像

发布于 2024-07-29 13:30:48 字数 81 浏览 3 评论 0原文

我正在寻找任何代码示例,展示如何将图像从 URL 提取到 Delphi TImage 组件中。

谢谢,

I am looking for any code samples that show how to pull images from URL into Delphi TImage component.

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

余厌 2024-08-05 13:30:49

最好使用此功能进行下载:

function DownloadFile(Url, DestFile: string): Boolean;
begin
   try
     Result := UrlDownloadToFile(nil, PChar(Url), PChar(DestFile), 0, nil) = 0;
   except
     Result := False;
   end;
end;

Better use this Function for downloading:

function DownloadFile(Url, DestFile: string): Boolean;
begin
   try
     Result := UrlDownloadToFile(nil, PChar(Url), PChar(DestFile), 0, nil) = 0;
   except
     Result := False;
   end;
end;
缺⑴份安定 2024-08-05 13:30:48

TMemoryStream 和 Indy 组件的帮助下。

uses
  GIFImg;

procedure TForm1.btn1Click(Sender: TObject);
var
  MS : TMemoryStream;
  GIf: TGIFImage;
begin
  MS := TMemoryStream.Create;
  GIf := TGIFImage.Create;
  try
    IdHTTP1.get('http://www.google.com/intl/en_ALL/images/logo.gif',MS);
    Ms.Seek(0,soFromBeginning);       
    Gif.LoadFromStream(MS);
    img1.Picture.Assign(GIF);

  finally
    FreeAndNil(GIF);
    FreeAndNil(MS);
  end;
end;

With help of TMemoryStream and Indy component.

uses
  GIFImg;

procedure TForm1.btn1Click(Sender: TObject);
var
  MS : TMemoryStream;
  GIf: TGIFImage;
begin
  MS := TMemoryStream.Create;
  GIf := TGIFImage.Create;
  try
    IdHTTP1.get('http://www.google.com/intl/en_ALL/images/logo.gif',MS);
    Ms.Seek(0,soFromBeginning);       
    Gif.LoadFromStream(MS);
    img1.Picture.Assign(GIF);

  finally
    FreeAndNil(GIF);
    FreeAndNil(MS);
  end;
end;
残花月 2024-08-05 13:30:48

代码也适用于 JPEG。

Code Worked for JPEG as well.

女中豪杰 2024-08-05 13:30:48

对于 这个项目,我使用了 Indy 组件(如第一个响应),但使用了线程内的代码。 对于下载大图像或大量图像很有用。 您可以在链接中看到项目的完整说明(西班牙语,但您可以使用自动翻译)。

在本例中,我使用它来下载此页面的所有图片。
这里我使用另一个组件 IdSSL:TIdSSLIOHandlerSocket,它是访问 https url 所必需的; 如果您必须访问http,则不需要它。

TDownImageThread的代码是(添加英文注释):

  {: Clase para descargar una imagen y almacenarla en disco.}
  {: Class to download image and save to disk}
  TDownImageThread = class(TThread)
  private
    FURLImage: string;
    FPathImage: string;
    FFileNameImage: string;
    // Internas
    ImageName: string;
    PathURL: string;
    // Componente
    idH:TidHTTP;
    IdSSL:TIdSSLIOHandlerSocket;
  public
    // redefinir métodos  // redefine methods
    constructor  Create(AURL:string; AOutPathImages:string);
    destructor Destroy; override;
    procedure Execute; override;
    {: URL de la imagen a descargar. //   URL to download}
    property URLImage:string read FURLImage write FURLImage;
    {: Path de disco local donde voy a almacenar la imagen.}
    {: Local path to save the images}
    property PathImage:string read FPathImage;
    {: Nombre completa (path+Nombre) de la imagen almacenada en disco local}
    {: complete name (path+name) of loval image}
    property FileNameImage:string read FFileNameImage;
  end;



....


{ TDownImageThread }
constructor TDownImageThread.Create(AURL, AOutPathImages: string);
var
  URI:TidURI;
begin

  // crear el thread suspendido  // Create suspended thread
  inherited Create(True);
  // Parámetros: URL y dir de salida   // Params URL and output dir.
  Self.FURLImage := AURL;
  Self.FPathImage := AOutPathImages;
  // Crear con URL    // create with URL 
  URI := TidURI.Create(AURL);
  try
    ImageName := URI.Document;
    PathURL := URI.Path;
  finally
    URI.Free;
  end;
end;

destructor TDownImageThread.Destroy;
begin
  inherited;
end;

//: recupara la imagen y la guarda en disco
procedure TDownImageThread.Execute();
var
  Stream:TFileStream;
  IdH:TidHTTP;
  IdSSL:TIdSSLIOHandlerSocket;
  path:string;
  dir:string;
begin
  // Directorio de salida  // output directory
  dir := AnsiReplaceText(PathURL, '/', STR_EMPTY);
  // Nombre vacío  // empty name
  if (ImageName = STR_EMPTY) then begin
    Exit;
  end;
  // Path de salida     // output path
  path := IncludeTrailingBackslash(IncludeTrailingBackslash(PathImage) +
           dir) + ImageName;
  // Crearlo por si no existe    // create it if not exist
  ForceDirectories(ExtractFilePath(path));
  try
    // Stream para la imagen    // Stream for the image
    Stream  := TFileStream.Create(path, fmCreate);
    try
      // Crear componente para acceder   /// Create the component in runtime
      IdH := TidHttp.Create(nil);
      IdH.ReadTimeout := 30000;
      // necessary to use HTTPS
      IdSSL := TIdSSLIOHandlerSocket.Create(nil);
      IdH.IOHandler := IdSSL;
      IdSSL.SSLOptions.Method := sslvTLSv1;
      IdSSL.SSLOptions.Mode := sslmUnassigned;
      idH.HandleRedirects := True;
      IdH.RedirectMaximum := 3;

      // proteccion
      try
        // Obtener la imagen   // get the image
        IdH.Get(Trim( FURLImage), Stream);
      except
        // Error al descargar la imagen   
        //..  Volcarlo al log
      end;
    finally
      // Liberar    // Free component
      idH.Free;
      // IdSSL.Free;
      Stream.Free;
    end;
    // Path de salida     // output path
    FFileNameImage := path;
  except
    // error al crear el fichero  // error on create file
    //...  Log
  end;
end;

使用它时,调用类似于这样:

// Crear un nuevo thread para descargar la imagen
// Create a new thread  LINK+output path
th := TDownImageThread.Create(mmLinks.Lines[i], pathImages);
// Procedimiento de retorno al finalizar
// procedure to return on thread finalize
th.OnTerminate := TerminateThread;
th.Resume;

For this project I used Indy components (like first response), but using the code inside a thread. Usefull for download big images or a big number of images. You can see the complete explaination of project in link (is in spanish but you can use automatic translation).

In this case I use it for download all images from this page.
Here I use another component IdSSL:TIdSSLIOHandlerSocket, necessary for access to an https url; If you must access to an http, don't need it.

The code of TDownImageThread is (added english comments):

  {: Clase para descargar una imagen y almacenarla en disco.}
  {: Class to download image and save to disk}
  TDownImageThread = class(TThread)
  private
    FURLImage: string;
    FPathImage: string;
    FFileNameImage: string;
    // Internas
    ImageName: string;
    PathURL: string;
    // Componente
    idH:TidHTTP;
    IdSSL:TIdSSLIOHandlerSocket;
  public
    // redefinir métodos  // redefine methods
    constructor  Create(AURL:string; AOutPathImages:string);
    destructor Destroy; override;
    procedure Execute; override;
    {: URL de la imagen a descargar. //   URL to download}
    property URLImage:string read FURLImage write FURLImage;
    {: Path de disco local donde voy a almacenar la imagen.}
    {: Local path to save the images}
    property PathImage:string read FPathImage;
    {: Nombre completa (path+Nombre) de la imagen almacenada en disco local}
    {: complete name (path+name) of loval image}
    property FileNameImage:string read FFileNameImage;
  end;



....


{ TDownImageThread }
constructor TDownImageThread.Create(AURL, AOutPathImages: string);
var
  URI:TidURI;
begin

  // crear el thread suspendido  // Create suspended thread
  inherited Create(True);
  // Parámetros: URL y dir de salida   // Params URL and output dir.
  Self.FURLImage := AURL;
  Self.FPathImage := AOutPathImages;
  // Crear con URL    // create with URL 
  URI := TidURI.Create(AURL);
  try
    ImageName := URI.Document;
    PathURL := URI.Path;
  finally
    URI.Free;
  end;
end;

destructor TDownImageThread.Destroy;
begin
  inherited;
end;

//: recupara la imagen y la guarda en disco
procedure TDownImageThread.Execute();
var
  Stream:TFileStream;
  IdH:TidHTTP;
  IdSSL:TIdSSLIOHandlerSocket;
  path:string;
  dir:string;
begin
  // Directorio de salida  // output directory
  dir := AnsiReplaceText(PathURL, '/', STR_EMPTY);
  // Nombre vacío  // empty name
  if (ImageName = STR_EMPTY) then begin
    Exit;
  end;
  // Path de salida     // output path
  path := IncludeTrailingBackslash(IncludeTrailingBackslash(PathImage) +
           dir) + ImageName;
  // Crearlo por si no existe    // create it if not exist
  ForceDirectories(ExtractFilePath(path));
  try
    // Stream para la imagen    // Stream for the image
    Stream  := TFileStream.Create(path, fmCreate);
    try
      // Crear componente para acceder   /// Create the component in runtime
      IdH := TidHttp.Create(nil);
      IdH.ReadTimeout := 30000;
      // necessary to use HTTPS
      IdSSL := TIdSSLIOHandlerSocket.Create(nil);
      IdH.IOHandler := IdSSL;
      IdSSL.SSLOptions.Method := sslvTLSv1;
      IdSSL.SSLOptions.Mode := sslmUnassigned;
      idH.HandleRedirects := True;
      IdH.RedirectMaximum := 3;

      // proteccion
      try
        // Obtener la imagen   // get the image
        IdH.Get(Trim( FURLImage), Stream);
      except
        // Error al descargar la imagen   
        //..  Volcarlo al log
      end;
    finally
      // Liberar    // Free component
      idH.Free;
      // IdSSL.Free;
      Stream.Free;
    end;
    // Path de salida     // output path
    FFileNameImage := path;
  except
    // error al crear el fichero  // error on create file
    //...  Log
  end;
end;

To use it, the call is similar to this:

// Crear un nuevo thread para descargar la imagen
// Create a new thread  LINK+output path
th := TDownImageThread.Create(mmLinks.Lines[i], pathImages);
// Procedimiento de retorno al finalizar
// procedure to return on thread finalize
th.OnTerminate := TerminateThread;
th.Resume;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文