Search code examples
pythonimagepython-2.7httplib

How to download an image with httplib?


If I have a direct link to the image, how do I properly download it?

conn = httplib.HTTPConnection("URL_BASE")
conn.request("GET", "/REST_OF_THE_URL.jpg", "", headers)
page = conn.getresponse()
page = page.read()
fail = open("image.jpg", "w")
fail.write(page)
fail.close()

This kind of succeeds, but there's something wrong with the data, as the images generally appear corrupt. So I'm assuming there's some extra data somewhere that isn't part of the image, but I don't know how to identify it nor how to remove it.


Solution

  • You need to open your image in binary mode:

    fail = open("image.jpg", "wb")
    

    or line separators that happen to appear in your data stream will be translated to your platform standard (so \r\n would be replaced with \r).