rDrama/files/helpers/images.py

36 lines
1.0 KiB
Python
Raw Normal View History

2021-10-15 14:08:27 +00:00
from PIL import Image as IImage, ImageSequence
from webptools import gifwebp
2022-01-21 19:55:42 +00:00
import time
2021-10-15 14:08:27 +00:00
2022-01-21 20:06:39 +00:00
def process_image(file=None, filename=None, resize=0):
2021-10-15 14:08:27 +00:00
2022-01-21 19:55:42 +00:00
if not filename: filename = f'/images/{time.time()}'.replace('.','')[:-5] + '.webp'
2022-01-22 18:41:47 +00:00
try:
if file:
file.save(filename)
i = IImage.open(file)
else: i = IImage.open(filename)
except: abort(400)
2022-01-21 23:37:56 +00:00
2021-10-15 14:08:27 +00:00
if resize:
2022-01-21 19:55:42 +00:00
size = resize, resize
2021-10-15 14:08:27 +00:00
frames = ImageSequence.Iterator(i)
def thumbnails(frames):
for frame in frames:
thumbnail = frame.copy()
thumbnail.thumbnail(size)
yield thumbnail
frames = thumbnails(frames)
om = next(frames)
om.info = i.info
2022-01-13 02:24:46 +00:00
om.save(filename, format="WEBP", save_all=True, append_images=list(frames), loop=0, method=6, allow_mixed=True)
2021-10-15 14:08:27 +00:00
elif i.format.lower() != "webp":
2022-01-21 19:55:42 +00:00
if i.format.lower() == "gif":
gifwebp(input_image=filename, output_image=filename, option="-mixed -metadata none -f 100 -mt -m 6")
2022-01-13 02:24:46 +00:00
else: i.save(filename, format="WEBP", method=6)
2021-10-15 14:08:27 +00:00
2021-12-26 04:03:58 +00:00
return f'/static{filename}'