Skip to content

Instantly share code, notes, and snippets.

@milosev1c
Created April 4, 2023 19:15
Show Gist options
  • Save milosev1c/6c152ddd44af985a2595c0f951f1cb25 to your computer and use it in GitHub Desktop.
Save milosev1c/6c152ddd44af985a2595c0f951f1cb25 to your computer and use it in GitHub Desktop.
WebpImageField for Django
from io import BytesIO
from django.db.models.fields.files import ImageField
from PIL import Image
"""
This field will automatically convert your jpg/png files to webp
Usage:
Replace your ImageField with this one.
Parameters:
webp_quality: Integer, 0-100, Defaults to 80. For lossy, 0 gives the smallest size and 100 the largest.
For lossless, this parameter is the amount of effort put into the compression:
0 is the fastest, but gives larger files compared to the slowest, but best, 100.
webp_lossless: if present and true, instructs the WebP writer to use lossless compression.
webp_method: Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 4.
"""
class WebPImageField(ImageField):
def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
self.webp_quality = kwargs.pop('webp_quality', 80)
self.webp_lossless = kwargs.pop('webp_lossless', False)
self.webp_method = kwargs.pop('webp_method', 4)
super(WebPImageField, self).__init__(verbose_name, name, width_field, height_field, **kwargs)
def save_form_data(self, instance, data):
if data:
image = Image.open(data)
image = image.convert("RGB")
webp_image_name = f"{data.name.rsplit('.', 1)[0]}.webp"
webp_image_bytes = BytesIO()
image.save(
webp_image_bytes,
"WEBP",
quality=self.webp_quality,
lossless=self.webp_lossless,
method=self.webp_method
)
webp_image_bytes.seek(0)
data.file = webp_image_bytes
data.name = webp_image_name
super().save_form_data(instance, data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment