Search code examples
django-filer

How to generate single thumbnail file using easy-thumbnails library in Django


I am using django-filer module using which I am uploading jpg/png images to the django project.

Django-filer is internally using easy-thumbnails which doesn't support webp format.

So they have provided a work around as below, https://easy-thumbnails.readthedocs.io/en/latest/ref/webp/

With this work around I am able to generate webp image as soon as someone upload jpg or png image.

However the generated images has different resolutions like below,

> /thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__48x48_q85_crop_subsampling-2_upscale.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__48x48_q85_crop_subsampling-2_upscale@2x.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__16x16_q85_crop_subsampling-2_upscale.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__16x16_q85_crop_subsampling-2_upscale@2x.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__32x32_q85_crop_subsampling-2_upscale.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__64x64_q85_crop_subsampling-2_upscale@2x.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__180x180_q85_crop_subsampling-2_upscale.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__180x180_q85_crop_subsampling-2_upscale@2x.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__32x32_q85_crop_subsampling-2_upscale@2x.jpg
> ./thumbnails/uploads/medical-microneedling-indications-for-a-new-dual-purpose-device.jpg__64x64_q85_crop_subsampling-2_upscale.jpg

What I need is only a single file with resolution 180x180.

Please advise how can I do that?

I tried to use aliases as mentioned at below link however it did not help, https://easy-thumbnails.readthedocs.io/en/latest/usage/#thumbnail-aliases


Solution

  • I found the answer and it can be controlled using the filter on filename as below,

    def store_as_webp(self, sender, **kwargs):
      img_basename = os.path.basename(sender.name)
      webp_path = sender.storage.path(f'./uploads/{img_basename}.webp')
      if re.search(r"180x180.*upscale@2x", webp_path):
        sender.image.save(webp_path, 'webp')
        
    def ready(self):
      thumbnail_created.connect(self.store_as_webp)