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. 在github上新建一个仓库并上传本地工程

    扫盲:在github上新建一个仓库并上传本地工程 http://1ke.co/course/194 我自己新建了个项目,一步一步流程如下. zhoudd@desay:~/桌面/mini_embed_d ...

  2. XSS注入学习

    引贴: http://mp.weixin.qq.com/s?__biz=MzIyMDEzMTA2MQ==&mid=2651148212&idx=1&sn=cd4dfda0b92 ...

  3. selinux-网络服务安全

    一.显示和设置selinux [root@localhost ~]# vim /etc/sysconfig/selinux //强制模式 许可模式 禁用模式 [root@localhost ~]# g ...

  4. pytorch rnn 2

    import torch import torch.nn as nn import numpy as np import torch.optim as optim class RNN(nn.Modul ...

  5. vue跳转页面传值怎么传?

    这是路由跳转: this.$router.push( { name: 'holderResult', params: { meetingId:self.$route.params.meetingId} ...

  6. AndroidManifest.xml中的注册组件

    界面跳转时Activity的识别方法有两种:第一种,通过name 第二种,通过<intent-filter> 通过配置文件中配置<intent-filter>来实现Activi ...

  7. 滑块控件CCControlSlider

    #include "cocos-ext.h" //包含头文件 using namespace cocos2d::extension;//引用命名空间 /** * 创建CCContr ...

  8. tensorflow训练自己的数据集实现CNN图像分类2(保存模型&测试单张图片)

    神经网络训练的时候,我们需要将模型保存下来,方便后面继续训练或者用训练好的模型进行测试.因此,我们需要创建一个saver保存模型. def run_training(): data_dir = 'C: ...

  9. python3_ftp文件传输

    Python中的ftplib模块 Python中默认安装的ftplib模块定义了FTP类,其中函数有限,可用来实现简单的ftp客户端,用于上传或下载文件 FTP的工作流程及基本操作可参考协议RFC95 ...

  10. adb常用操作

    1.安装程序 adb -s serialno install -r path 2.切换电源 adb -s serialno shell input keyevent 26 3.主页键 adb -s s ...