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

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

 1 def changeimgtobase64(img_url, max_width=600, max_height=400, resize=True):
 2     """
 3 
 4     :param img_url: 图片地址
 5     :param max_width: 长边
 6     :param max_height: 短边
 7     :param resize: 是否改变大小
 8     :return:
 9     """
10     if img_url.startswith('/'):
11         img_url = img_url[1:]
12     img_url = os.path.join(settings.ROOT_PATH, img_url)
13     rotate = False  # 是否短边为宽
14     result = ''
15     try:
16         img = Image.open(img_url)
17         width, height = img.size
18         if resize:
19             # width, height = img.size
20             if width < height:
21                 # 使图片长边为宽
22                 rotate = True
23                 width, height = height, width
24             if width > max_width or height > max_height:
25                 width = min([width, max_width])
26                 height = min([height, max_height])
27                 if rotate:
28                     img = img.resize((height, width), Image.ANTIALIAS)
29                 else:
30                     img = img.resize((width, height), Image.ANTIALIAS)
31         else:
32             while width*height > 1024 * 1024 * 2:  # 图片像素点大于2M就缩小0.9,直至小于2M
33                 width, height = int(width*0.9), int(height*0.9)
34                 log.debug('%s:%s,%s' % (u'图片缩小至', width,height))
35             img = img.resize((width, height), Image.ANTIALIAS)
36 
37         img_buffer = io.BytesIO()
38         if img_url.find('jpeg') == -1:
39             # 将png等非jpg格式转为jpg
40             img = img.convert("RGB")
41         img.save(img_buffer, format='JPEG')
42         byte_data = img_buffer.getvalue()
43         img_buffer.close()
44         base64_data = base64.b64encode(byte_data)
45         s = base64_data.decode()
46         result = 'data:image/jpg;base64,%s' % s
47     except Exception, e:
48         exc_type, exc_obj, exc_tb = sys.exc_info()
49         alertmsg = u'%s %s Exception. %s:%s' % (platform.node(), exc_tb.tb_lineno, sys._getframe().f_code.co_name, e)
50         log.error(alertmsg)
51     return result

 

posted @ 2019-09-02 09:45  小哥豪  阅读(705)  评论(0编辑  收藏  举报