python2.7 PIL 图片收缩并转码base64

需求:将图片转为base64,最大允许图片大小600px*400px

 1 import io,  base64, sys
 2 from PIL import Image
 3 
 4 def changeimgtobase64(img_url, max_width=600, max_height=400):
 5     """
 6     :param img_url: 图片地址
 7     :param max_width: 长边
 8     :param max_height: 短边
 9     :return:
10     """
11     rotate = False  # 是否短边为宽
12     result = ''
13     try:
14         img = Image.open(img_url)
15         width, height = img.size
16         if width < height:
17             # 使图片长边为宽
18             rotate = True
19             width, height = height, width
20         if width > max_width or height > max_height:
21             width = min([width, max_width])
22             height = min([height, max_height])
23             if rotate:
24                 img = img.resize((height, width), Image.ANTIALIAS) # Image.ANTIALIAS参数平滑图片,使图片更清晰
25             else:
26                 img = img.resize((width, height), Image.ANTIALIAS)
27 
28         img_buffer = io.BytesIO()  # 生成buffer
29         img.save(img_buffer, format='JPEG')
30         byte_data = img_buffer.getvalue()
31         base64_data = base64.b64encode(byte_data)
32         s = base64_data.decode()
33         result = 'data:image/jpg;base64,%s' % s
34     except Exception.e:
35         exc_type, exc_obj, exc_tb = sys.exc_info()
36         alertmsg = u'%s %s Exception. %s --- %s' % (exc_tb.tb_lineno, sys._getframe().f_code.co_name, code, e)
37         log.error(alertmsg)
38     return result

 

转载于:https://www.cnblogs.com/shuangpang/p/11444863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值