python裁剪base64编码的图片

简介

今天遇到需要裁剪base64字符串的PNG图片,并返回base64格式字符串的任务,捣鼓半天。
裁剪代码如下:

def deal_inspect_img(base64_str):
    """裁剪base64字符串的图片"""
    base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
    byte_data = base64.b64decode(base64_data)
    # BytesIO 对象
    image_data = io.BytesIO(byte_data)
    # 得到Image对象
    img = Image.open(image_data)
    # 裁剪图片(左,上,右,下),笛卡尔坐标系
    img2 = img.crop((962, 485, 1897, 810))

    # BytesIO 对象
    imgByteArr = io.BytesIO()
    # 写入BytesIO对象
    img2.save(imgByteArr, format='PNG')
    # 获得字节
    imgByteArr = imgByteArr.getvalue()
    base64_str = base64.b64encode(imgByteArr)
    return base64_str

如果需要保存

base64_str = 'xxxxxxxxxxxxxxxxxxxxxxx'
imgdata = base64.b64decode(base64_str)
with open('iss.png', 'wb') as f:
    f.write(imgdata)

转载于:https://www.cnblogs.com/haoabcd2010/p/10691085.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值