def save_image(image, destination=None, filename=None, **options):
"""
Save a PIL image.
"""
if destination is None:
destination = BytesIO()
filename = filename or ''
# Ensure plugins are fully loaded so that Image.EXTENSION is populated.
Image.init()
format = Image.EXTENSION.get(os.path.splitext(filename)[1].lower(), 'JPEG')
if format in ('JPEG', 'WEBP'):
options.setdefault('quality', 85)
saved = False
if format == 'JPEG':
if settings.THUMBNAIL_PROGRESSIVE and (
max(image.size) >= settings.THUMBNAIL_PROGRESSIVE):
options['progressive'] = True
try:
image.save(destination, format=format, optimize=1, **options)
saved = True
except IOError:
# Try again, without optimization (PIL can't optimize an image
# larger than ImageFile.MAXBLOCK, which is 64k by default). This
# shouldn't be triggered very often these days, as recent versions
# of pillow avoid the MAXBLOCK limitation.
pass
if not saved:
image.save(destination, format=format, **options)
if hasattr(destination, 'seek'):
destination.seek(0)
return destination
评论列表
文章目录