[英]How to convert bytes to text and back to bytes?
I want to convert a picture into bytes and place it in a text file and then open that text file and convert it to a picture again.我想将图片转换为字节并将其放入文本文件中,然后打开该文本文件并将其再次转换为图片。
png=open("C:\\Users\\myUser\\Desktop\\n.png","rb")
pngbytes=png.read()
newf=open("C:\\Users\\myUser\\Desktop\\newf.txt","w")
newf.write(str(pngbytes))
newf.close()
newf=open("C:\\Users\\myUser\\Desktop\\newf.txt","r")
newpng=open("C:\\Users\\myUser\\Desktop\\newpng.png","wb")
strNewf=newf.read()
newpng.write(strNewf.encode())
newpng.close()
png.close()
newf.close()
The image is created but can't be displayed.图像已创建但无法显示。
You can get your code to work by replacing strNewf.encode()
with eval(strNewf)
.您可以通过将
strNewf.encode()
替换为eval(strNewf)
来使您的代码正常工作。
This works because the string you've created with str(pngbytes)
gives you the string representation of the bytes, eval
simply interprets that representation to give you the bytes again.这是有效的,因为您使用
str(pngbytes)
创建的字符串为您提供了字节的字符串表示,而eval
只是简单地解释该表示以再次为您提供字节。
Why you'd want to do this is entirely unclear however - what are you trying to achieve?然而,你为什么要这样做是完全不清楚的——你想达到什么目的? Because it seems that there's better ways to go about it...
因为似乎有更好的方法来解决它......
Here you have a full working example.这里有一个完整的工作示例。
This will: 1) Load an image file into memory.这将: 1) 将图像文件加载到内存中。 2) Convert the image into raw text.
2) 将图像转换为原始文本。 3) Save the image as text into a different file.
3) 将图像作为文本保存到不同的文件中。 4) Read the text file and convert it to the original image.
4) 读取文本文件并将其转换为原始图像。
import base64
# Open image as bytes.
with open("8000_loss.png", "rb") as f:
png_bytes = f.read()
# Convert bytes to text.
type(png_bytes) # bytes
png_str = base64.b64encode(png_bytes).decode()
type(png_str) # string
# Save text to file.
with open("wolverine.txt", "w") as f:
f.write(png_str)
# Read file as text.
with open("wolverine.txt", "r") as f:
png_str2 = f.read()
# Convert text to bytes.
type(png_str2) # string
png_bytes2 = base64.b64decode(png_str2.encode())
type(png_bytes2) # bytes
# Validate the image has not been modified
assert png_bytes == png_bytes2
你不清楚内置函数'str'的结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.