feat: complete lab 7 for grade 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""Bounded subprocess for untrusted image decoding and resizing."""
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
# Linux runtime. macOS does not implement RLIMIT_AS with the same semantics.
|
||||
if sys.platform.startswith('linux'):
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (15, 16))
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def fit(image, bound):
|
||||
width, height = image.size
|
||||
largest = max(width, height)
|
||||
if largest <= bound:
|
||||
return image
|
||||
return image.resize((max(1, width * bound // largest), max(1, height * bound // largest)),
|
||||
Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def render(directory, version):
|
||||
with Image.open(directory / 'original', formats=("PNG", "JPEG")) as source:
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if 'A' in image.getbands() or 'transparency' in image.info:
|
||||
rgba = image.convert('RGBA')
|
||||
del image
|
||||
image = Image.new('RGB', rgba.size, 'white')
|
||||
image.paste(rgba, mask=rgba.getchannel('A'))
|
||||
del rgba
|
||||
else:
|
||||
image = image.convert('RGB')
|
||||
image.info.clear()
|
||||
jpeg_quality, webp_quality = {1: (85, 82), 2: (90, 88)}[version]
|
||||
fit(image, 256).save(directory / 'thumbnail', format='JPEG', quality=jpeg_quality)
|
||||
ImageOps.fit(image, (128, 128), Image.Resampling.LANCZOS).save(
|
||||
directory / 'crop', format='JPEG', quality=jpeg_quality)
|
||||
fit(image, 1280).save(directory / 'optimized', format='WEBP', quality=webp_quality, method=4)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
render(Path(sys.argv[1]), int(sys.argv[2]))
|
||||
except (OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
sys.exit(15)
|
||||
Reference in New Issue
Block a user