Abhishek Kumar
Abhishek Kumar

Reputation: 43

How can i store raw data into a PNG file in Python?

>>> def qrcodegenerate(nbr):
...     res = requests.get("https://chart.googleapis.com/chart?cht=qr&chs=300x330&choe=UTF-8&chl="+str(nbr))
...     print(res.url)
...     data =res.text
...     with open("C:\wamp\www\Paymentapi\qrcode\qr_"+str(nbr)+'.png','w',encoding="utf-8") as f:
...             f.write(data)
...
>>> qrcodegenerate(5697)

Here I am calling API to generate a QR code and I want to save into a PNG file.

The QR code is being generated, but it's not being saved correctly.

Upvotes: 1

Views: 357

Answers (1)

Andrea Corbellini
Andrea Corbellini

Reputation: 17751

PNG files contain binary data, not UTF-8 text.

What you need to do is:

  1. Use res.content (binary) instead of res.text (text).

  2. Open the file in binary mode (wb) instead of text mode (w), without specifying an encoding.

The resulting code should look like this:

def qrcodegenerate(nbr):
    res = requests.get('https://chart.googleapis.com/chart?cht=qr&chs=300x330&choe=UTF-8&chl=' + str(nbr))
    print(res.url)
    data = res.content
    with open('...', 'wb') as f:
        f.write(data)

Upvotes: 3

Related Questions