Solved

Download File with Indy

Posted on 2006-06-29
9
2,048 Views
Last Modified: 2011-05-06
How can I download an image using IdHTTP ?
0
Comment
Question by:crystyan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 10

Expert Comment

by:atul_parmar
ID: 17008899
Hi, just set the following properties and run it.
  IdFTP1.Username := '';
  IdFTP1.Password := '';
  IdFTP1.Host := '';
  IdFTP1.Connect(True);
  IdFTP1.Get(FileName,true);
  IdFTP1.Disconnect;
0
 
LVL 10

Expert Comment

by:atul_parmar
ID: 17008922
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 17009524
DUH, the OP asked to do it using HTTP, NOT FTP...
This code downloads a JPEG into a TImage using idHTTP.

uses ..., jpeg;

procedure TForm1.Button1Click(Sender: TObject);
var
  strStream: String;
  memStream: TMemoryStream;
  jpegimg: TJPEGImage;
begin
  try
    strStream := idhttp1.Get ('http://www.delphipages.com/images/backplain.jpg');
  except
    ShowMessage('Image was not found');
    Exit;
  end;
  memStream := TMemoryStream.Create;
  jpegimg   := TJPEGImage.Create;
  try
    memStream.Write(strStream[1], Length(strStream));
    memStream.Position := 0;
    jpegimg.LoadFromStream(memStream);
    Image1.Picture.Assign(jpegimg);
  finally
    memStream.Free;
    jpegimg.Free;
  end;
end;

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:atul_parmar
ID: 17009565
Thanx Eddie. I should move now.
0
 

Author Comment

by:crystyan
ID: 17010290
hi Eddie,

what if the picture is not a jpeg ?
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 17010928
OK, I'll rewrite it for different images. Remember that GIF will be hard to do unless
you use a 3rd-party library like Mike Lischke's GraphicsEX.
0
 

Author Comment

by:crystyan
ID: 17010949
I have GraphhicsEx. so if u can make it for ANY kinda image that GraphicsEx supports.

THANKS
0
 
LVL 26

Expert Comment

by:EddieShipman
ID: 17011102
ok. am working on it now.
0
 
LVL 26

Accepted Solution

by:
EddieShipman earned 250 total points
ID: 17013509
ok, thanks go to Peter Below on the Borland newsgroups for helpinh out on the GetIMGType function.
This demo handles the image types: .jpg, .png, .bmp, .gif, .psp, .tif

I am putting URLs for actual images on my website.

You can see how to add more, if needed, in the code.

Note: Make sure you define LZW in order to get GIF working


Unit source:

unit ugetimg;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, JPEG, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP, StdCtrls, ExtCtrls, IdURI, GraphicEx,
  StrUtils, ComCtrls;

type
  TForm1 = class(TForm)
    IdHTTP1: TIdHTTP;
    Panel1: TPanel;
    Panel2: TPanel;
    ProgressBar1: TProgressBar;
    ListBox1: TListBox;
    Panel3: TPanel;
    Image1: TImage;
    procedure IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCount: Integer);
    procedure ListBox1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    function GetImageFromWeb(AURL: string): TGraphic;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//
// Returns TGraphic class based on extension
//
function GetIMGType(const AFileName: String):TGraphicClass;
type
  TImgDescriptor = record ext: string; classtype: TGraphicClass; end;
const
  IMGTypes: array[0..5] of TImgDescriptor =
    ((ext:'.jpg'; classtype: TJPEGImage),
     (ext:'.png'; classtype: TPNGGraphic),
     (ext:'.bmp'; classtype: TBitmap),
     (ext:'.gif'; classtype: TGIFGraphic),
     (ext:'.psp'; classtype: TPSPGraphic),
     (ext:'.tif'; classtype: TTIFFGraphic));
var
  I: Integer;
begin
  Result := nil;
  for I := Low(ImgTypes) to High(ImgTypes) do
    if AnsiEndsText(ImgTypes[I].ext, AFileName) then
    begin
      Result := ImgTypes[I].classtype;
      Exit;
    end;
  raise Exception.CreateFmt('No graphic class available for file "%s"',
    [aFilename]);
end;

function TForm1.GetImageFromWeb(AURL: string): TGraphic;
var
  strStream: String;
  memStream: TMemoryStream;
  IMG: TGraphic;
  URI: TidURI;
  s: String;
begin
  try
    IdHTTP1.OnWork := nil;
    idhttp1.Head(AURL);
    s := IdHTTP1.Response.RawHeaders.Values['Content-Length'];
    ProgressBar1.Max := StrToInt(s);
    IdHTTP1.OnWork := IdHTTP1Work;
    strStream := idHTTP1.Get(AURL);
  except
    ShowMessage('Image was not found');
    Exit;
  end;
  memStream := TMemoryStream.Create;
  URI := TIdURI.Create(AURL);
  try
    IMG := GetIMGType(URI.Document).Create;
  finally
    URI.Free;
  end;
  try
    memStream.Write(strStream[1], Length(strStream));
    memStream.Position := 0;
    IMG.LoadFromStream(memStream);
    if (IMG.Width < 546) and
       (IMG.Height < 446) then
    begin
      Image1.Stretch := False;
      Image1.Height  := IMG.Height;
      Image1.Width   := IMG.Width;
    end
    else
    begin
      Image1.Stretch := True;
      Image1.Height  := 446;
      Image1.Width   := 546;
    end;
    Image1.Picture.Assign(IMG);
  finally
    memStream.Free;
    IMG.Free;
    ProgressBar1.Position := 0;
  end;
end;

procedure TForm1.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
  ProgressBar1.Position := AWorkCount;
end;

procedure TForm1.ListBox1Click(Sender: TObject);
begin
  GetImageFromWeb('http://www.austinmetrobaseball.com/images/'+ ListBox1.Items[ListBox1.ItemIndex]);
end;

end.

DFM Source:
object Form1: TForm1
  Left = 275
  Top = 197
  Width = 696
  Height = 480
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Panel1: TPanel
    Left = 0
    Top = 0
    Width = 142
    Height = 446
    Align = alLeft
    BevelOuter = bvNone
    TabOrder = 0
    object Panel2: TPanel
      Left = 0
      Top = 0
      Width = 142
      Height = 112
      Align = alTop
      BevelOuter = bvNone
      Caption = 'Panel2'
      TabOrder = 0
      object ListBox1: TListBox
        Left = 0
        Top = 0
        Width = 142
        Height = 112
        Align = alClient
        ItemHeight = 13
        Items.Strings = (
          'action_sporting_goods.gif'
          '2005_yardbirds.png'
          '2005_drays.bmp'
          '2005_ironbirds.jpg'
          '2005_bombers.psp'
          '2005_rockies.tif')
        TabOrder = 0
        OnClick = ListBox1Click
      end
    end
    object ProgressBar1: TProgressBar
      Left = 121
      Top = 112
      Width = 21
      Height = 334
      Align = alRight
      Orientation = pbVertical
      TabOrder = 1
    end
  end
  object Panel3: TPanel
    Left = 142
    Top = 0
    Width = 546
    Height = 446
    Align = alClient
    BevelOuter = bvNone
    TabOrder = 1
    object Image1: TImage
      Left = 0
      Top = 0
      Width = 546
      Height = 446
      Align = alClient
      Stretch = True
    end
  end
  object IdHTTP1: TIdHTTP
    MaxLineAction = maException
    ReadTimeout = 0
    OnWork = IdHTTP1Work
    AllowCookies = True
    ProxyParams.BasicAuthentication = False
    ProxyParams.ProxyPort = 0
    Request.ContentLength = -1
    Request.ContentRangeEnd = 0
    Request.ContentRangeStart = 0
    Request.ContentType = 'text/html'
    Request.Accept = 'text/html, */*'
    Request.BasicAuthentication = False
    Request.UserAgent = 'Mozilla/3.0 (compatible; Indy Library)'
    HTTPOptions = [hoForceEncodeParams]
    Left = 97
    Top = 409
  end
end
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Suggested Courses
Course of the Month11 days, 18 hours left to enroll

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question