【问题标题】:how to convert a PIL image to string and then convert it back to PIL image? The convsersion is to be done without saving it to a new file如何将 PIL 图像转换为字符串,然后将其转换回 PIL 图像?无需将其保存到新文件即可完成转换
【发布时间】:2020-12-27 16:00:55
【问题描述】:

我目前正在这样做以进行字节串转换,但我需要转换为字符串。

img=Image.fromarray(img)
output = io.BytesIO()
img.save(output, format="png")
image_as_string = output.getvalue()
img=Image.open(io.BytesIO(image_as_string))
img.save('strimg.png')

【问题讨论】:

  • 为什么需要将其转换为字符串?字符串用于字符,而不用于图像。 Python 中的字符串不是任意的字节串,并且在您的图像数据中肯定会有字节子序列在被视为 Unicode 代码点时毫无意义。因此,如果您尝试转换为字符串,您可能会遇到编码错误。字节串可以让你做你正在做的事情,而不必担心字节在解释为字符时可能意味着什么。
  • 转base64怎么样? en.m.wikipedia.org/wiki/Base64
  • @wuerfelfreak 我尝试过使用 base64,但是当我尝试将其编码回图像时出现错误。
  • @BoarGules 我想将其转换为字符串,因为我想对图像执行一些加密操作。
  • 你可以加密一个字节串。事实上,大多数加密库函数期望字节串,因为坚持使用Python字符串会阻止像你这样的用户做你想做的事情。

标签: python arrays python-3.x python-imaging-library


【解决方案1】:

这是我使用 base64 的解决方案。

import base64

img = Image.open("test.png")
output = io.BytesIO()
img.save(output, format="png")
image_as_string = base64.b64encode(output.getvalue())

#encrypting/decrypting

img=Image.open(io.BytesIO(base64.b64decode(image_as_string)))
img.save('string.png') 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多