64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
import io
|
|
import warnings
|
|
from PIL import Image, ImageOps
|
|
|
|
|
|
class ImagePipeline:
|
|
def __init__(self, settings, version=1):
|
|
self.settings = settings
|
|
self.jpeg_quality = 85 if version == 1 else 90
|
|
self.webp_quality = 80 if version == 1 else 85
|
|
Image.MAX_IMAGE_PIXELS = settings.max_pixels
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
|
|
def render(self, data):
|
|
with Image.open(io.BytesIO(data)) as source:
|
|
self.validate(source)
|
|
source.load()
|
|
ImageOps.exif_transpose(source, in_place=True)
|
|
image = self.flatten(source)
|
|
try:
|
|
yield self.scaled(image, "thumbnail", 256, "JPEG", self.jpeg_quality)
|
|
yield self.crop(image)
|
|
yield self.scaled(image, "optimized", 1280, "WEBP", self.webp_quality)
|
|
finally:
|
|
image.close()
|
|
|
|
def validate(self, image):
|
|
if image.format not in ("PNG", "JPEG"):
|
|
raise ValueError("invalid_image")
|
|
if image.width * image.height > self.settings.max_pixels:
|
|
raise ValueError("image_too_large")
|
|
|
|
def flatten(self, image):
|
|
if "A" in image.getbands() or "transparency" in image.info:
|
|
with image.convert("RGBA") as alpha:
|
|
result = Image.new("RGB", alpha.size, "white")
|
|
result.paste(alpha, mask=alpha.getchannel("A"))
|
|
return result
|
|
return image.convert("RGB")
|
|
|
|
def scaled(self, image, name, limit, format_name, quality):
|
|
divisor = max(limit, image.width, image.height)
|
|
size = (max(1, image.width * limit // divisor), max(1, image.height * limit // divisor))
|
|
with image.resize(size, Image.Resampling.LANCZOS) as resized:
|
|
return self.encode(resized, name, format_name, quality)
|
|
|
|
def crop(self, image):
|
|
with ImageOps.fit(
|
|
image, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)
|
|
) as cropped:
|
|
return self.encode(cropped, "crop", "JPEG", self.jpeg_quality)
|
|
|
|
def encode(self, image, name, format_name, quality):
|
|
output = io.BytesIO()
|
|
image.info.clear()
|
|
image.save(output, format=format_name, quality=quality)
|
|
return {
|
|
"name": name,
|
|
"data": output.getvalue(),
|
|
"width": image.width,
|
|
"height": image.height,
|
|
"content_type": "image/jpeg" if format_name == "JPEG" else "image/webp",
|
|
}
|