Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django aws s3 image resize on upload and access to various resized image

I would like to be able resize my uploaded image to various size categories:

  • original
  • medium (500kb)
  • small (200kb)

And save it to AWS S3. And later be able to access it. One strategy is to save it in filename_small.jpg, filename_medium.jpg, have a helper function to be able to append the _small, _medium to access those files. Im not sure how to save all the different files (resized) and then access it with the helper.

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py

class MediaStorage(S3Boto3Storage):
    location = 'media'
    file_overwrite = False

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
...
    face_image = models.FileField(upload_to=upload_to('employee/face_image/'), blank=True, storage=MediaStorage())

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['POST'])
def update_employee_image(request):
...
    employee = Employee.objects.get(id = employee_id)
    employee.face_image = face_image_obj
    employee.save()

I am using django-storages and S3Boto3Storage. My full working project is in the git links.

like image 892
Axil Avatar asked Nov 20 '17 02:11

Axil


1 Answers

Depending on what your use case is I would suggesting using sorl-thumbnail which works with django-storages and will handle the resizing for you, and means you don't have to do the work of managing different sizes yourself.

Instead of defining specific file sizes to store the image for, you would define thumbnail sizes in the places you want to use them, e.g.,

{% thumbnail item.image "300" crop="center" as im %}
    <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}">
{% endthumbnail %}

This would produce a thumbnail of maximum width 300px, which would get generated the first time and saved on s3.

The app has a low level API that you can use if you need to generate and fetch thumbnails outside of a template context:

from sorl.thumbnail import get_thumbnail

im = get_thumbnail(my_file, '100x100', crop='center', quality=99)
like image 163
solarissmoke Avatar answered Oct 24 '22 02:10

solarissmoke