1

I am using the requests module to connect to a php script which returns a PNG image. If I do so :

import requests
r=requests.get("http://location/script.php", cookies=cookies)
fp = open("image.png", "wb")
fp.write(r.text) #r.text is the binary data for the PNG returned by that php script
fp.close()

But it gave a UnicodeEncodeError while writing, so I used fp.write(r.text.encode("utf-8")) instead of fp.write(r.text). And the file was created, but I'm not able to view it in an image viewer(it gives an error). However, if I right-click and save the PNG returned by that script in Firefox, I can view it in the same image viewer after it's saved. So I'm guessing there is a problem with the way I'm writing that image data to a file. Is there some other way I could do it?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mayank Kumar
  • 1,133
  • 3
  • 13
  • 20

1 Answers1

4

r.text is not the binary data. That attribute gives you the decoded text, a Unicode value.

You'd want to use r.content instead, or stream the image to a file setting stream=True and copying from the r.raw file object.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343