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:35:41 +00:00
|
|
|
|
|
|
|
if file: i = IImage.open(file)
|
2022-01-22 00:41:42 +00:00
|
|
|
else: i = IImage.open(filename)
|
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":
|
2022-01-22 18:35:41 +00:00
|
|
|
file.save(filename)
|
|
|
|
time.sleep(0.1)
|
2022-01-21 19:55:42 +00:00
|
|
|
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}'
|