2

Hello I am trying to download a .PNG image from a website, but I need my headers sent in the request to download image. My end goal is to get the image loaded directly into a Stream, rather than saving it to a file.

This is the code I get the Image's HTML with:

public string Request(string type, string page, string data = "", string referer = "")
{
    using(TcpClient tcp = new TcpClient(this.SiteName, this.Port))
    {
        byte[] headers = Encoding.Default.GetBytes(this.MakeHeaders(type, page, referer, data));
        using (NetworkStream ns = tcp.GetStream())
        {
            ns.Write(headers, 0, headers.Length);
            using (StreamReader sr = new StreamReader(ns, Encoding.Default))
            {
                string html = sr.ReadToEnd();
                return html;
            }
        }
    } 
}

The headers I send look like this:

GET /image.php HTTP/1.1
Host: greymatter.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Connection: close
Cache-Control: max-age=0
Cookie: PHPSESSID=s0v17eafosj5ctb5v6keu3lh57; __cfduid=d10aef4fcfd052e1f59fba9832cedf4491374611636

The PNG file I save locally starts with:

67f
‰PNG

The saved PNG file is corrupt - can't be viewed! I don't understand why this is happening?

Zacharious
  • 515
  • 4
  • 13
  • Does the actual request end with a php? If so then I'd consider that to be where your one of your issues start. A request header for a png would look like "GET /careers/Img/testimonial-quote.png HTTP/1.1" – Terrance Jul 23 '13 at 20:54

1 Answers1

1

The request is for that of a php document. The individual assets of a web site are downloaded separately. So a single TCP request may not cover what you are intending to do. I'd recommend Fiddler for looking at the calls made for requesting a web page.

Also I'd look at using Image.FromStream() to convert the stream to png. (Just a pref. Working with byte arrays and streams for data has always been particularly error prone for me.)

Its used something like this.

byte[] imageData = MyRequestFunction(Url); //MyRequestFunction function from here
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);
stream.Close();

Additionally web requests are made for what you are doing. This example might help.
How to read picture from URL and show it on my page

Community
  • 1
  • 1
Terrance
  • 11,764
  • 4
  • 54
  • 80