Solved

Download File with Indy

Posted on 2006-06-29
9
2,041 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Objective: - This article will help user in how to convert their numeric value become words. How to use 1. You can copy this code in your Unit as function 2. than you can perform your function by type this code The Code   (CODE) The Im…
Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

910 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

22 Experts available now in Live!

Get 1:1 Help Now