需求:将图片转为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