Python:如何将图像转换为STRING并返回? [英] Python: How to turn an IMAGE into a STRING and back?

查看:309
本文介绍了Python:如何将图像转换为STRING并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图片像这样加载到PIL.Image中:

I have an image like this loaded into a PIL.Image:

现在我想将其转换为 python字符串,并且它不应该是二进制的,我该怎么做? 因为当我尝试编码时,出现以下错误:

And now I want to turn it into a python string, and it should not be binary, how do I do this? Because when I tried to encode I get the following error:

我的代码:

from PIL import Image

img = Image.open("testImage.jpeg")
string = img.tobytes()
string = string.decode("ascii")

输出:

Traceback (most recent call last):
  File "/Users/tomschimansky/Desktop/SenderMAIN.py", line 5, in <module>
    string = string.decode("ascii")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

当此方法有效时,我还想将字符串变回图像.

When this works I also want to turn the string back into an image.

对我来说也不起作用的其他方法:

Other methods that also don't worked for me:

  • 直接使用open("file","rb")从文件中读取图像,然后对其进行编码.
  • 使用codecs库对其进行编码. (string = codecs.encode(string, "base64"))
  • 使用base64库对其进行编码(能够将其转换为字符串,但是字符串看起来像这样:///////.(仅斜线))
  • Read the image directly from file with open("file","rb") and then encode it.
  • encode it with the codecs library. (string = codecs.encode(string, "base64"))
  • encode it with the base64 library (was able to convert it to string but the string looked like this: ///////. (only slashes))

感谢您的回答!

推荐答案

您可以转换为这样的字符串:

You can convert to a string like this:

import base64

with open("image.png", "rb") as image:
    b64string = base64.b64encode(image.read())

这应该为您提供与在Terminal中运行此结果相同的结果:

That should give you the same results as if you run this in Terminal:

base64 < image.png

您可以像这样将字符串转换回PIL图像:

And you can convert that string back to a PIL Image like this:

from PIL import Image
import io

f = io.BytesIO(base64.b64decode(b64string))
pilimage = Image.open(f)

这应该等同于终端机中的以下内容:

That should be equivalent to the following in Terminal:

base64 -D < "STRING" > recoveredimage.png


请注意,如果要通过LoRa发送此文件,则最好发送文件的PNG编码版本,就像我在这里一样,因为它已压缩并且会花费更少的时间.或者,您可以发送文件的扩展内存版本,但该文件的内存版本将扩大近50%. PNG文件为13kB.扩展后的内存版本将为100 * 60 * 3或18kB.


Note that if you are sending this over LoRa, you are better off sending the PNG-encoded version of the file like I am here as it is compressed and will take less time. You could, alternatively, send the expanded out in-memory version of the file but that would be nearly 50% larger. The PNG file is 13kB. The expanded out in-memory version will be 100*60*3, or 18kB.

这篇关于Python:如何将图像转换为STRING并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆