Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
:rtype: Asset
"""
mime_type = MimeType(mime_type)
pil_format = PillowProcessor.__mime_type_to_pillow_type[mime_type]
pil_options = dict(PillowProcessor.__format_defaults.get(mime_type, {}))
format_config = dict(self.config.get(mime_type.type, {}))
format_config.update(self.config.get(str(mime_type), {}))
image_buffer = io.BytesIO()
if mime_type == MimeType('image/png') and image.mode != 'P':
use_zopfli = format_config.get('zopfli', False)
if use_zopfli:
import zopfli
zopfli_png = zopfli.ZopfliPNG()
# Convert 16-bit per channel images to 8-bit per channel
zopfli_png.lossy_8bit = False
# Allow altering hidden colors of fully transparent pixels
zopfli_png.lossy_transparent = True
# Use all available optimization strategies
zopfli_png.filter_strategies = format_config.get('zopfli_strategies', '0me')
pil_options.pop('optimize', False)
essence = io.BytesIO()
image.save(essence, 'PNG', optimize=False, **pil_options)
essence.seek(0)
optimized_data = zopfli_png.optimize(essence.read())
image_buffer.write(optimized_data)
else:
image.save(image_buffer, pil_format, **pil_options)
elif mime_type == MimeType('image/jpeg'):
output_format = "jpeg"
# convert / optimize
output_image_bytes = None
if output_format == "jpeg":
output_image_bytes = pyguetzli.process_pil_image(
image, int(options["jpeg_quality"] * 100))
else:
pass
image_io = io.BytesIO()
image.save(image_io, format="PNG", optimize=False)
image_io.seek(0)
image_bytes = image_io.read()
# Optimize using zopflipng
zopflipng = zopfli.ZopfliPNG()
zopflipng.lossy_8bit = True
zopflipng.lossy_transparent = True
zopflipng.filter_strategies = "01234mepb"
zopflipng.iterations = 20
zopflipng.iterations_large = 7
output_image_bytes = zopflipng.optimize(image_bytes)
# write to output_file
output_file.seek(0)
output_file.truncate()
output_file.write(output_image_bytes)