简体   繁体   中英

converting png formatted text received from API to png file - python

trying to make a program in python that request the following api and return with a QRcode. this QRcode i get back is actually formatted text and i need to put that into a PNG file. this is my code

import requests
import os


user = os.getlogin()
print("Hi there, " + user)
text = input("Enter a word: ")
request = requests.get("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + text)
response = request.text

file = open("output.txt", "w")
file.write(response)
file.close()
print("\nDone !")

put i get this error when trying to save it as png or text:

'charmap' codec can't encode character '\�' in position 0: character maps to <undefined>

Not sure what you mean when you say:

this QRcode i get back is actually formatted text and i need to put that into a PNG file

The response you get is not plain-text. You can check the response headers' Content-Type field and confirm that it is an image ( image/png ). All you have to do is write the response bytes to a file:

def main():

    import requests

    text = "test"
    url = f"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data={text}"

    response = requests.get(url)
    response.raise_for_status()

    with open("output.png", "wb") as file:
        file.write(response.content)

    print("Done.")

    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())

If you want to save response as png you can do it like this

import requests
import os

user = os.getlogin()
print("Hi there, " + user)
text = input("Enter a word: ")
request = requests.get(
    "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + text)

open(text+'.png', 'wb').write(request.content)

print("Done !")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM