OCR-PIL.Image与Base64 String的互相转换

1. 基本环境

  • py2: python2.7.13
  • py3: python3.6.2
  • PIL: pip(2/3) install pillow, PIL库已不再维护,而pillow是PIL的一个分支,如今已超越PIL

2. Convert PIL.Image to Base64 String

  • py2 :先使用CStringIO.StringIO把图片内容转为二进制流,再进行base64编码
# -*- coding: utf-8 -*-

import base64
from cStringIO import StringIO

# pip2 install pillow
from PIL import Image


def image_to_base64(image_path):
    img = Image.open(image_path)
    output_buffer = StringIO()
    img.save(output_buffer, format='JPEG')
    binary_data = output_buffer.getvalue()
    base64_data = base64.b64encode(binary_data)
    return base64_data
  • py3:python3中没有cStringIO,对应的是io,但却不能使用io.StringIO来处理图片,它用来处理文本的IO操作,处理图片的应该是io.BytesIO
import base64
from io import BytesIO

# pip3 install pillow
from PIL import Image

# 若img.save()报错 cannot write mode RGBA as JPEG
# 则img = Image.open(image_path).convert('RGB')
def image_to_base64(image_path):
    img = Image.open(image_path)
    output_buffer = BytesIO()
    img.save(output_buffer, format='JPEG')
    byte_data = output_buffer.getvalue()
    base64_str = base64.b64encode(byte_data)
    return base64_str

3. Convert Base64 String to PIL.Image

  • py2:
# -*- coding: utf-8 -*-

import re
import base64
from cStringIO import StringIO

from PIL import Image


def base64_to_image(base64_str, image_path=None):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    binary_data = base64.b64decode(base64_data)
    img_data = StringIO(binary_data)
    img = Image.open(img_data)
    if image_path:
        img.save(image_path)
    return img
  • py3:
import re
import base64
from io import BytesIO

from PIL import Image


def base64_to_image(base64_str, image_path=None):
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    image_data = BytesIO(byte_data)
    img = Image.open(image_data)
    if image_path:
        img.save(image_path)
    return img

4. 参考网址

[1] https://stackoverflow.com/questions/16065694/is-it-possible-to-create-encodeb64-from-image-object

[2] https://stackoverflow.com/questions/31826335/how-to-convert-pil-image-image-object-to-base64-string

[3] https://stackoverflow.com/questions/26070547/decoding-base64-from-post-to-use-in-pil

 

 

 

 

 

发布了652 篇原创文章 · 获赞 1574 · 访问量 297万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览