rDrama/files/helpers/images.py

31 lines
943 B
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
i = IImage.open(file)
if not filename: filename = f'/images/{time.time()}'.replace('.','')[:-5] + '.webp'
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":
i.save(filename)
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}'