简体   繁体   中英

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

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.

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. 2) Convert the image into raw text. 3) Save the image as text into a different file. 4) Read the text file and convert it to the original image.

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'的结果

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