https://www.jianshu.com/p/2ff8e6f98257

PIL.Image与Base64 String的互相转换

2018.01.18 19:02* 字数 281 阅读 39评论 0喜欢 0

0.环境

  • 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把图片内容转为二进制流,再进行base64编码
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

2. Convert Base64 String to PIL.Image

要注意的是图片内容转化所得的Base64 String是不带有头信息/html标签(data:image/jpeg;base64,)的,这是在h5使用的时候需要添加用来声明数据类型的,如果拿到的Base64 String带了这个标签的话,需要处理一下,这里从参考的博客中找了一种正则处理方法。

  • py2:
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

PIL.Image与Base64 String的互相转换的更多相关文章

  1. python base64 编解码,转换成Opencv,PIL.Image图片格式

    二进制打开图片文件,base64编解码,转成Opencv格式: # coding: utf-8 import base64 import numpy as np import cv2 img_file ...

  2. JavaScript – Convert Image to Base64 String

    From: https://bytenota.com/javascript-convert-image-to-base64-string/ his post shows you two approac ...

  3. 图片和base64编码字符串 互相转换,图片和byte数组互相转换

    图片和base64编码字符串 互相转换 import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; ...

  4. (Java) byte[] 和 base64 字符串之间的转换

    import org.apache.commons.codec.binary.Base64; public class UtilHelper { //base64字符串转byte[] public s ...

  5. js实现图片的Blob base64 ArrayBuffer 的各种转换

    一.相关基础知识 构造函数 FileReader() 返回一个新构造的FileReader 事件处理 FileReader.onabort  处理abort事件.该事件在读取操作被中断时触发. Fil ...

  6. base64与byte[]之间转换

    主要是根据BASE64Encoder 和BASE64Decoder 进行操作实现,具体例子如下: BASE64Encoder encode = new BASE64Encoder(); //将byte ...

  7. C#中char[]与string之间的转换

    string 转换成 Char[] string ss = "abcdefg"; char[] cc = ss.ToCharArray(); Char[] 转换成string st ...

  8. C字符串和C++中string的区别 &&&&C++中int型与string型互相转换

    在C++中则把字符串封装成了一种数据类型string,可以直接声明变量并进行赋值等字符串操作.以下是C字符串和C++中string的区别:   C字符串 string对象(C++) 所需的头文件名称 ...

  9. 如何在Byte[]和String之间进行转换

    源自C#与.NET程序员面试宝典. 如何在Byte[]和String之间进行转换? 比特(b):比特只有0 1,1代表有脉冲,0代表无脉冲.它是计算机物理内存保存的最基本单元. 字节(B):8个比特, ...

随机推荐

  1. nodejs与c语言交互应用实例

    nodejs与c/c++交互目前主流的方式有两种,node addon c++ 和 node-ffi . 1.node addon c++ 1)nodejs从c语言读取数据 addon.c #incl ...

  2. SDUT3143:Combinatorial mathematics(组合数学)

    题意:传送门 题目描述 As you know, shadow95 is pretty good at maths, especially combinatorial mathematics. Now ...

  3. django 用户注册功能实现

    增加views的类 class RegisterView(View): def get(self, request): return render(request, 'register.html', ...

  4. smarty模板(转载)

    一.smarty的程序设计部分: 在smarty的模板设计部分我简单的把smarty在模板中的一些常用设置做了简单的介绍,这一节主要来介绍一下如何在smarty中开始我们程序设计.下载Smarty文件 ...

  5. 京东AI平台 春招实习生面试--NLP(offer)

    给offer了 开心.春招第一个offer!!! 2018.4.11 update 1面: 只有1面, 面试官还是个老乡.. 1.自我介绍 如何学的AI相关的知识? 2.介绍百度的实习 3.拿到一个问 ...

  6. Python 实例3—三级菜单

    老男孩培训学习: ''' Author:Ranxf ''' menu = { '北京': { '海淀': { '五道口': { 'soho': {}, '网易': {}, 'google': {} } ...

  7. DevOps简单介绍

    jenkins作为测试环境代码发布工具,sonar作为静态代码检查工具,idea作为开发工具,jira作为缺陷管理平台,upstream作为code review工具(正在研究).DevOps最近比较 ...

  8. 清除list或者map集合,减少内存的占用率

    1.在编写程序对数据处理的时候我们经常会使用到list和map集合,有些时候我们存到集合里的数据只是暂时性的,在验证完或者使用完之后尽量对list或者map清空,及list.clear()后者map. ...

  9. ubuntu搭建tiny4412环境【学习笔记】

    一.安装完系统之后需要执行如下步骤 1.sudo apt-get update 更新软件源 2.sudo apt-get install vsftpd openssh-server nfs-kerne ...

  10. websocket 重连解决方案

    1.websocket 重连的脚本:https://github.com/joewalnes/reconnecting-websocket                 reconnecting-w ...