【问题标题】:How to get images from URL in DelphiDelphi如何从URL获取图片
【发布时间】:2010-11-16 16:36:42
【问题描述】:

我正在寻找显示如何将图像从 URL 拉入 Delphi TImage 组件的任何代码示例。

谢谢,

【问题讨论】:

    标签: delphi indy


    【解决方案1】:

    借助 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;
    

    【讨论】:

    • 您甚至可以不使用 TGifImage 而使用 img1.Picture.LoadFromStream(MS);
    • 警告: 如果TIdHTTP.Get 中存在异常,则此代码将释放未初始化的GIF 变量。如果您没有在之前进入相应的“try”部分进行初始化,请不要在“finally”部分中使用变量。
    • 不,拉斯,你不能那样做。 TPicture.LoadFromStream 受保护,不公开。而且它只是调用Bitmap.LoadFromStream,所以它无论如何也不知道如何加载GIF数据。
    • 谢谢 Rob,我很着急,特别是 Gif 方面,我希望将 Stream 直接存储到 TImage 中,但发现它不可用。
    • Mohammed,该代码适用于您发布的 GIF。我很感激。我无法使用 JPEG(我使用 D2009)。我在上面发布了我的代码。任何建议将不胜感激谢谢,克里斯又名格林纳
    【解决方案2】:

    代码也适用于 JPEG。

    【讨论】:

    • 添加“使用JPEG”,我用GIF单元制作了我的例子,你需要使用Jpeg一个。
    • 绿色,你没有使用正确的Get方法。如果你想让它填充一个流,你需要记住将流作为参数传递。 Get 的单参数版本将资源内容作为函数返回值中的字符串返回。
    • 是的,Rob,我发现了我的错误。再次感谢大家的帮助。
    • 您应该编辑您的第一篇文章或将 cmets 添加到相关答案中。
    【解决方案3】:

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

    在这种情况下,我用它来下载所有图像from this page
    这里我使用了另一个组件IdSSL:TIdSSLIOHandlerSocket,这是访问 https url 所必需的;如果您必须访问 http,则不需要它。

    TDownImageThread的代码是(加了英文cmets):

      {: 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;
    

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-03-22
        • 2014-08-04
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 2011-09-26
        • 2016-10-04
        相关资源
        最近更新 更多