4

我有一个带有图像字段的标准 Django 表单。上传图片时,我想确保图片不大于 300 像素 x 300 像素。这是我的代码:

def post(request):
    if request.method == 'POST':
        instance = Product(posted_by=request.user)
        form = ProductModelForm(request.POST or None, request.FILES or None)
        if form.is_valid():
           new_product = form.save(commit=False)
           if 'image' in request.FILES:
              img = Image.open(form.cleaned_data['image'])
              img.thumbnail((300, 300), Image.ANTIALIAS)

              # this doesnt save the contents here...
              img.save(new_product.image)

              # ..because this prints the original width (2830px in my case)
              print new_product.image.width

我面临的问题是,我不清楚如何将Image类型转换为 ImageField 类型。

4

6 回答 6

3

From the documentation on ImageField's save method:

Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object.

This means you would need to convert the PIL.Image (img) to a Python file object, and then convert the Python object to a django.core.files.File object. Something like this (I have not tested this code) might work:

img.thumbnail((300, 300), Image.ANTIALIAS)

# Convert PIL.Image to a string, and then to a Django file
# object. We use ContentFile instead of File because the
# former can operate on strings.
from django.core.files.base import ContentFile
djangofile = ContentFile(img.tostring())
new_product.image.save(filename, djangofile)
于 2011-08-11T06:59:22.467 回答
1

如何使用标准图像字段https://github.com/humanfromearth/django-stdimage

于 2011-08-11T06:55:53.430 回答
1

你去,只需改变一点以满足您的需要:

class PhotoField(forms.FileField, object):

    def __init__(self, *args, **kwargs):
        super(PhotoField, self).__init__(*args, **kwargs)
        self.help_text = "Images over 500kb will be resized to keep under 500kb limit, which may result in some loss of quality"

    def validate(self,image):
        if not str(image).split('.')[-1].lower() in ["jpg","jpeg","png","gif"]:
            raise ValidationError("File format not supported, please try again and upload a JPG/PNG/GIF file")

    def to_python(self, image):
        try:
            limit = 500000
            num_of_tries = 10
            img = Image.open(image.file)
            width, height = img.size
            ratio = float(width) / float(height)

            upload_dir = settings.FILE_UPLOAD_TEMP_DIR if settings.FILE_UPLOAD_TEMP_DIR else '/tmp'
            tmp_file = open(os.path.join(upload_dir, str(uuid.uuid1())), "w")
            tmp_file.write(image.file.read())
            tmp_file.close()

            while os.path.getsize(tmp_file.name) > limit:
                num_of_tries -= 1
                width = 900 if num_of_tries == 0 else width - 100
                height = int(width / ratio)
                img.thumbnail((width, height), Image.ANTIALIAS)
                img.save(tmp_file.name, img.format)
                image.file = open(tmp_file.name)
                if num_of_tries == 0:
                    break                    
        except:
            pass
        return image

来源:http: //james.lin.net.nz/2012/11/19/django-snippet-reduce-image-size-during-upload/

于 2012-11-22T18:04:06.977 回答
1

这是一个可以解决这个问题的应用程序:django-smartfields

from django.db import models

from smartfields import fields
from smartfields.dependencies import FileDependency
from smartfields.processors import ImageProcessor

class Product(models.Model):
    image = fields.ImageField(dependencies=[
        FileDependency(processor=ImageProcessor(
            scale={'max_width': 300, 'max_height': 300}))
    ])
于 2014-12-24T04:35:25.707 回答
0

在这里尝试我的解决方案:https ://stackoverflow.com/a/25222000/3731039

强调

  • 使用 Pillow 进行图像处理(需要两个包:libjpeg-dev、zlib1g-dev)
  • 使用 Model 和 ImageField 作为存储
  • 将 HTTP POST 或 PUT 与 multipart/form 一起使用
  • 无需手动将文件保存到磁盘。
  • 创建多个分辨率并存储它们的尺寸。
于 2014-08-09T19:29:03.203 回答
0

你可以使用我的库django-sizedimagefield,它没有额外的依赖并且使用起来非常简单。

于 2017-06-27T13:31:32.103 回答