环境
- py2:python2.7.13
- py3:python3.7.5
- PIL:pip(2/3) install pillow,PIL库已经不再维护,而pillow是PIL的一个分支,如今已超越PIL
1、Convert PIL.Image to Base64 String
- py2:先使用CStringIO.StringIO把图片内容转为二进制流,再进行base64编码
1 import base64 2 from cStringIO import StringIO 3 4 # pip2 install pillow 5 from PIL import Image 6 7 8 def image_to_base64(image_path): 9 img = Image.open(image_path) 10 output_buffer = StringIO() 11 img.save(output_buffer, format='JPEG') 12 binary_data = output_buffer.getvalue() 13 base64_data = base64.b64encode(binary_data) 14 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
2、Convert Base64 String to PIL.Image
要注意的是图片内容转化所得的Base64 String是不带有头信息/html标签(data:image/jpeg;base64,)的,这是在h5使用的时候需要添加用来声明数据类型的,如果拿到的Base64 String带了这个标签的话,需要处理一下。
- py2:
1 import re 2 import base64 3 from cStringIO import StringIO 4 5 from PIL import Image 6 7 8 def base64_to_image(base64_str, image_path=None): 9 base64_data = re.sub('^data:image/.+;base64,', '', base64_str) 10 binary_data = base64.b64decode(base64_data) 11 img_data = StringIO(binary_data) 12 img = Image.open(img_data) 13 if image_path: 14 img.save(image_path) 15 return img
- py3:
1 import re 2 import base64 3 from io import BytesIO 4 5 from PIL import Image 6 7 8 def base64_to_image(base64_str, image_path=None): 9 base64_data = re.sub('^data:image/.+;base64,', '', base64_str) 10 byte_data = base64.b64decode(base64_data) 11 image_data = BytesIO(byte_data) 12 img = Image.open(image_data) 13 if image_path: 14 img.save(image_path) 15 return img
参考:https://www.cnblogs.com/changbaishan/p/8618035.html