#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File : imgConvertUtils.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date : 2021-06-21
from PIL import Image
from PIL import ImageFile
import math
import io
ImageFile.LOAD_TRUNCATED_IMAGES = True
class ImageConvert:
def __init__(self):
pass
def convert2rb(self,input_rb,targetWidth,quality=95):
input_file = io.BytesIO(input_rb)
sImg = Image.open(input_file)
ext = sImg.format
w, h = sImg.size
if targetWidth and w >= targetWidth:
rate = round(targetWidth / w, 4)
height = math.floor(rate * h)
# print(targetWidth,height)
dImg = sImg.resize((targetWidth, height), Image.ANTIALIAS)
output = io.BytesIO()
flag = 'RGBA' if sImg.format.lower() == 'png' else 'RGB'
dImg.convert(flag).save(output, format=ext, quality=quality)
return output.getvalue()
else:
return input_rb
if __name__ == '__main__':
with open(r'D:\Desktop\报销发票附件样例\2.jpg',mode='rb') as f:
input_rb = f.read()
img = ImageConvert()
output_rb = img.convert2rb(input_rb,1080)
with open(r'D:\Desktop\报销发票附件样例\输出4.jpg','wb+') as f:
f.write(output_rb)