Python PIL模块Image对象、字节流对象转二进制字节流

    今天有一个问题就是需要将网络字节流或者是Image对象转化为二进制字节流数据,之后借助于base64模块实现编码最终post到服务接口端,这里没有过多要去讲解的,直接看实现就行。

#!usr/bin/env python
# encoding:utf-8
from __future__ import division

'''
__Author__:沂水寒城
功能: Python PIL模块Image对象、字节流对象转二进制字节流
'''


import io
import os
import requests
from PIL import Image
import matplotlib.pyplot as plt



def image2Binary():
    '''
    Image对象转化为二进制字节流对象
    '''
    img=Image.open('a.png')
    new=img.crop([0,67,400,340])
    plt.clf()
    plt.figure(figsize=(8,6))
    plt.subplot(1,2,1)
    plt.imshow(img)
    plt.title("original")
    plt.subplot(1,2,2)
    plt.imshow(new)
    plt.title("crop")
    plt.show()
    #图像文件可以从本地静态文件中直接读取为二进制字节流形式
    binary_str=open('a.png','rb').read()
    #已经被Image类读取成为Image对象后也可以转化为二进制字节流形式
    img_byte=io.BytesIO()
    new.save(img_byte,format='PNG')
    binary_str2=img_byte.getvalue()
    return binary_str,binary_str2


def bytes2Binary():
    '''
    网络字节流数据转化为二进制节流对象
    '''
    url="https://a.png"  #测试图片url
    response=requests.get(url)
    #网络图像字节流数据可以直接被Image类转化为Image对象
    im=Image.open(io.BytesIO(response.content))
    img_byte=io.BytesIO()
    im.save(img_byte,format='PNG')
    binary_str=img_byte.getvalue()
    return binary_str




if __name__ == '__main__':
    binary_str,binary_str2=image2Binary()
    binary_str=bytes2Binary()

 

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Together_CZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值