Solved

Download File with Indy

Posted on 2006-06-29
9
2,039 Views
Last Modified: 2011-05-06
How can I download an image using IdHTTP ?
0
Comment
Question by:crystyan
  • 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
 
LVL 10

Expert Comment

by:atul_parmar
ID: 17009565
Thanx Eddie. I should move now.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

760 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now