问题
I'm trying to send json dict that should contain Pillow image as one of his fields, to do that I have to convert the image to string.
I tried to use pillow function:
image.toString()
but still got it as bytes, so I tried to encode it:
buff = BytesIO()
image.save(buff, format="JPEG")
img_str = base64.b64encode(buff.getvalue())
but still got it as bytes. How can I convert Pillow images to format that can be saved in json file?
回答1:
In the comments, Mark Setchell suggests calling .decode('ascii')
on the result of your b64encode
call. I agree that this will work, but I think base64encoding to begin with is introducing an unnecessary extra step that complicates your code.*
Instead, I suggest directly decoding the bytes returned by image.tostring
. The only complication is that the bytes object can contain values larger than 128, so you can't decode it with ascii
. Try using an encoding that can handle values up to 256, such as latin1
.
from PIL import Image
import json
#create sample file. You don't have to do this in your real code.
img = Image.new("RGB", (10,10), "red")
#decode.
s = img.tobytes().decode("latin1")
#serialize.
with open("outputfile.json", "w") as file:
json.dump(s, file)
(*but, to my surprise, the resulting json file is still smaller than one made with a latin1 encoding, at least for my sample file. Use your own judgement to determine whether file size or program clarity is more important.)
回答2:
I use the following to exchange Pillow images via json.
import json
from PIL import Image
import numpy as np
filename = "filename.jpeg"
image = Image.open(filename)
json_data = json.dumps(np.array(image).tolist())
new_image = Image.fromarray(np.array(json.loads(json_data), dtype='uint8'))
来源:https://stackoverflow.com/questions/56428037/what-is-the-best-way-to-save-pil-image-in-json