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

2024-09-30 06:26:08 发布

您现在位置: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()

图像已创建,但无法显示。你知道吗


Tags: txtclosereadpng图片openuserswrite
3条回答

通过用eval(strNewf)替换strNewf.encode(),可以使代码正常工作。你知道吗

这是因为用str(pngbytes)创建的字符串提供了字节的字符串表示形式,eval只是解释该表示形式以再次提供字节。你知道吗

你为什么要这样做是完全不清楚的,但是-你想实现什么?因为似乎有更好的方法。。。你知道吗

这里有一个完整的工作示例。你知道吗

这将: 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

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

相关问题 更多 >

    热门问题