From d9f1864900b91afd64a775def22e2f9f5da97ad4 Mon Sep 17 00:00:00 2001 From: yumoqing Date: Wed, 27 Nov 2019 18:56:02 +0800 Subject: [PATCH] add image thumb handle --- ahserver/imgThumb.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 ahserver/imgThumb.py diff --git a/ahserver/imgThumb.py b/ahserver/imgThumb.py new file mode 100644 index 0000000..620f8af --- /dev/null +++ b/ahserver/imgThumb.py @@ -0,0 +1,35 @@ +from PIL import Image +from io import BytesIO + +def imageThumb(imgfilepath,width=None,height=None): + im = Image.open(imgfilepath) + mode = im.mode + if mode not in ('L', 'RGB'): + if mode == 'RGBA': + alpha = im.split()[3] + bgmask = alpha.point(lambda x: 255-x) + im = im.convert('RGB') + # paste(color, box, mask) + im.paste((255,255,255), None, bgmask) + else: + im = im.convert('RGB') + + w, h = im.size + if not width and not height: + width = 256 + if width: + height = int(float(width) * float(h) / float(w)) + else: + width = int(float(height) * float(w) / float(h)) + thumb = im.resize((width,height),Image.ANTIALIAS) + f = BytesIO() + thumb.save(f,format='jpeg',quality=60) + im.close() + v = f.getvalue() + with open('thumb.jpg','wb') as x: + x.write(v) + return v + + +if __name__ == '__main__': + imageThumb("/home/ymq/media/pictures/2019-08/IMG_20190804_113014.jpg", width=256)