【问题标题】:How to convert PIL Image.image object to base64 string? [duplicate]如何将 PIL Image.image 对象转换为 base64 字符串? [复制]
【发布时间】:2015-10-27 20:45:16
【问题描述】:

我正在尝试以将其旋转 90 角的方式操作 base64 编码图像。完成此操作后,我想将其转换回 base64 字符串。但遗憾的是还无法实现这一目标。

这是我到目前为止所做的:

image_string = StringIO(base64.b64decode(base64_string_here))
image = Image.open(image_string)
angle = 90
rotated_image = image.rotate( angle, expand=1 )

请帮我把这个 rotate_image 转换成 base64 字符串。

这是rotated_image 的dir()

['_Image__transformer', '__doc__', '__getattr__', '__init__', '__module__','__repr__','_copy','_dump','_expand','_makeself', '_new'、'category'、'convert'、'copy'、'crop'、'draft'、'filter'、 '格式','format_description','fromstring','getbands','getbbox', 'getcolors'、'getdata'、'getextrema'、'getim'、'getpalette'、 'getpixel'、'getprojection'、'histogram'、'im'、'info'、'load'、 '模式','偏移','调色板','粘贴','点','putalpha','putdata', “putpalette”、“putpixel”、“量化”、“只读”、“调整大小”、“旋转”、 'save', 'seek', 'show', 'size', 'split', 'tell', 'thumbnail', 'tobitmap', 'tostring', 'transform', 'transpose', 'verify']

【问题讨论】:

    标签: python python-imaging-library


    【解决方案1】:

    Python 3

    import base64
    from io import BytesIO
    
    buffered = BytesIO()
    image.save(buffered, format="JPEG")
    img_str = base64.b64encode(buffered.getvalue())
    

    Python 2

    import base64
    import cStringIO
    
    buffer = cStringIO.StringIO()
    image.save(buffer, format="JPEG")
    img_str = base64.b64encode(buffer.getvalue())
    

    【讨论】:

    • 我想说在python3.4中你应该写from io import BytesIObuffer = BytesIO()。另请记住,buffer 已经是一个现有的内置名称(可能使用buffered)。 The fine docs.
    • IOError: cannot write mode RGBA as JPEG
    • @User 这意味着图像具有 Alpha 通道(称为图像中的透明度级别)。如果您可以安全地摆脱它,您可以将图像转换为 RGB,然后再将其保存并转换为下一行的 base64 字符串:image = image.convert("RGB")
    • 如果有人要写入图像,这是必要的img_base64 = bytes("data:image/jpeg;base64,", encoding='utf-8') + img_str
    • 对不起,但不起作用:我得到一个像“b'iVBORw0KGgoAAAA....”这样的字符串,也就是字节字符串......我想要的是规范的base64字符串,以“=”结尾=" ...
    猜你喜欢
    • 2017-12-20
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多