【问题标题】:django aws s3 image resize on upload and access to various resized imagedjango aws s3 图像在上传和访问各种调整大小的图像时调整大小
【发布时间】:2018-05-03 05:06:51
【问题描述】:

我希望能够将我上传的图片调整为各种尺寸类别:

  • 原创
  • 中等 (500kb)
  • 小 (200kb)

并将其保存到 AWS S3。以后可以访问它。 一种策略是将其保存在 filename_small.jpg、filename_medium.jpg 中,并具有一个辅助函数,以便能够附加 _small、_medium 以访问这些文件。我不确定如何保存所有不同的文件(调整大小),然后使用帮助程序访问它。

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()

我正在使用 django-storages 和 S3Boto3Storage。我的完整工作项目在 git 链接中。

【问题讨论】:

  • 我不确定是否将整个东西与 django-storage/Amazon 集成,但请查看 VersatileImageField 以获得多种尺寸的图像和大量图像管理功能。

标签: python django file-upload resize django-storage


【解决方案1】:

根据您的用例,我建议使用sorl-thumbnail,它与django-storages 配合使用,将为您处理大小调整,这意味着您不必自己管理不同的大小。

您可以在要使用它们的地方定义缩略图大小,而不是定义特定的文件大小来存储图像,例如,

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

这将生成maximum width 300px 的缩略图,它会在第一次生成并保存在 s3 上。

如果您需要在模板上下文之外生成和获取缩略图,则可以使用该应用程序的低级 API:

from sorl.thumbnail import get_thumbnail

im = get_thumbnail(my_file, '100x100', crop='center', quality=99)

【讨论】:

  • 谢谢,我会看看它是如何工作的。从说明中我不清楚它是否会生成多个尺寸以保存在 S3 中。或者在 S3 中保存一个大小,然后调整它的大小以供显示(这对性能再次不利)我确实看到 THUMBNAIL_FORCE_OVERWRITE = True,我想知道这实际上是做什么的。
  • 生成多种尺寸。
  • 它有效,我用 get_thumbnail 试过了。在 S3 存储桶中,它将这些缩略图保存在不同的目录“缓存”下,实际上希望全部在同一目录中。
  • 有一个THUMBNAIL_PREFIX 设置,默认为cache/,您可以更改它。只是要非常小心你把它改成什么,因为clear_thumbnail 管理命令可以用来破坏整个目录。
猜你喜欢
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2015-08-06
  • 2011-10-04
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多