将从 API 收到的 png 格式文本转换为 png 文件 - python
converting png formatted text received from API to png file - python
尝试在 python 中制作一个程序,请求以下 api 和 return 以及二维码。
我返回的这个 QRcode 实际上是格式化文本,我需要将其放入 PNG 文件中。
这是我的代码
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 !")
尝试将其另存为 png 或文本时出现此错误:
'charmap' codec can't encode character '\ufffd' in position 0: character maps to <undefined>
不确定你说的是什么意思:
this QRcode i get back is actually formatted text and i need to put
that into a PNG file
您得到的响应不是 plain-text。您可以检查响应 headers' Content-Type
字段并确认它是图像 (image/png
)。您所要做的就是将响应字节写入文件:
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())
如果你想将响应保存为 png 你可以这样做
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 !")
尝试在 python 中制作一个程序,请求以下 api 和 return 以及二维码。 我返回的这个 QRcode 实际上是格式化文本,我需要将其放入 PNG 文件中。 这是我的代码
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 !")
尝试将其另存为 png 或文本时出现此错误:
'charmap' codec can't encode character '\ufffd' in position 0: character maps to <undefined>
不确定你说的是什么意思:
this QRcode i get back is actually formatted text and i need to put that into a PNG file
您得到的响应不是 plain-text。您可以检查响应 headers' Content-Type
字段并确认它是图像 (image/png
)。您所要做的就是将响应字节写入文件:
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())
如果你想将响应保存为 png 你可以这样做
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 !")