2

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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.