0

How can I view images from a website in my application using language C#.

I don't want to download all the page, I just want view the pictures in my application.

thirtydot
  • 224,678
  • 48
  • 389
  • 349

3 Answers3

2

You can use the HTML Agility Pack to find <img> tags.

Robert Paulson
  • 17,603
  • 5
  • 34
  • 53
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

You will need to download the html for the page using WebRequest class in System.Net.

You can then parse the HTML (using HTML Agility Pack) extract the URLs for the images and download the images, again using the WebRequest class.

Here is some sample code to get you started:

static public byte[] GetBytesFromUrl(string url)
{
    byte[] b;
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
    WebResponse myResp = myReq.GetResponse();

    Stream stream = myResp.GetResponseStream();
    using (BinaryReader br = new BinaryReader(stream))
    {

        b = br.ReadBytes(100000000);
        br.Close();
    }
    myResp.Close();
    return b;
}

You can use this code to download the raw bytes for a given URL (either the web page or the images themselves).

James Gaunt
  • 14,631
  • 2
  • 39
  • 57
  • Yes that is possible too http://stackoverflow.com/questions/1694388/webclient-vs-httpwebrequest-httpwebresponse – James Gaunt Feb 18 '11 at 00:20
  • hi guys for now i still have a same problem because when i have byte array but i can't take any pictures from url pls just give me the second step. thanx a lot – Nour Aldein Feb 18 '11 at 09:36
0
/// Returns the content of a given web adress as string.
/// </summary>
/// <param name="Url">URL of the webpage</param>
/// <returns>Website content</returns>
public string DownloadWebPage(string Url)
{
  // Open a connection
  HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(Url);

  // You can also specify additional header values like 
  // the user agent or the referer:
  WebRequestObject.UserAgent    = ".NET Framework/2.0";
  WebRequestObject.Referer  = "http://www.example.com/";

  // Request response:
  WebResponse Response = WebRequestObject.GetResponse();

  // Open data stream:
  Stream WebStream = Response.GetResponseStream();

  // Create reader object:
  StreamReader Reader = new StreamReader(WebStream);

  // Read the entire stream content:
  string PageContent = Reader.ReadToEnd();

  // Cleanup
  Reader.Close();
  WebStream.Close();
  Response.Close();

  return PageContent;
}
Cosmin
  • 21,216
  • 5
  • 45
  • 60