0.環(huán)境
- py2: python2.7.13
- py3: python3.6.2
- PIL: pip(2/3) install pillow, PIL庫已不再維護,而pillow是PIL的一個分支铺根,如今已超越PIL
1.Convert PIL.Image to Base64 String
- py2 :
先使用CStringIO.StringIO把圖片內(nèi)容轉(zhuǎn)為二進制流洛波,再進行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,對應(yīng)的是io侨颈,但卻不能使用io.StringIO來處理圖片惨缆,它用來處理文本的IO操作辟灰,處理圖片的應(yīng)該是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
2. Convert Base64 String to PIL.Image
要注意的是圖片內(nèi)容轉(zhuǎn)化所得的Base64 String是不帶有頭信息/html標簽(data:image/jpeg;base64,)的,這是在h5使用的時候需要添加用來聲明數(shù)據(jù)類型的凯旭,如果拿到的Base64 String帶了這個標簽的話概耻,需要處理一下,這里從參考的博客中找了一種正則處理方法尽纽。
- 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
3. 參考
https://stackoverflow.com/questions/16065694/is-it-possible-to-create-encodeb64-from-image-object
https://stackoverflow.com/questions/31826335/how-to-convert-pil-image-image-object-to-base64-string
https://stackoverflow.com/questions/26070547/decoding-base64-from-post-to-use-in-pil