如何将字节转换为文本并转换回字节?

时间:2019-07-26 03:40:49

标签: python

我想将图片转换为字节并将其放置在文本文件中,然后打开该文本文件,然后再次将其转换为图片。

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()

图像已创建但无法显示。

3 个答案:

答案 0 :(得分:0)

通过将strNewf.encode()替换为eval(strNewf),可以使代码正常工作。

之所以可行,是因为您使用str(pngbytes)创建的字符串为您提供了字节的字符串表示形式,eval只是将其解释为再次为您提供了字节。

但是,为什么要这样做完全不清楚,您想实现什么?因为似乎有更好的解决方法...

答案 1 :(得分:0)

这里有一个完整的示例。

这将: 1)将图像文件加载到内存中。 2)将图像转换为原始文本。 3)将图像作为文本保存到其他文件中。 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

答案 2 :(得分:0)

您不清楚内置函数'str'的结果

相关问题