4

画像フィールドを持つ標準の Django フォームがあります。画像をアップロードするときは、画像が 300px × 300px 以下であることを確認したいと思います。これが私のコードです:

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

ImageField のsave メソッドに関するドキュメントから:

content 引数は、Python の組み込みファイル オブジェクトではなく、django.core.files.File のインスタンスである必要があることに注意してください。

つまり、PIL.Image( img) を Python ファイル オブジェクトに変換してから、Python オブジェクトをオブジェクトに変換する必要がありdjango.core.files.Fileます。このようなもの (私はこのコードをテストしていません) がうまくいくかもしれません:

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

これを処理できるアプリがあります: 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 に答える
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 に答える
0

ここで私のソリューションを試してください: https://stackoverflow.com/a/25222000/3731039

ハイライト

  • 画像処理に Pillow を使用 (2 つのパッケージが必要: libjpeg-dev、zlib1g-dev)
  • Model と ImageField をストレージとして使用する
  • multipart/form での HTTP POST または PUT の使用
  • ファイルを手動でディスクに保存する必要はありません。
  • 複数の解像度を作成し、それらの寸法を保存します。
于 2014-08-09T19:29:03.203 に答える
0

これには、私のライブラリdjango-sizedimagefieldを使用できます。追加の依存関係がなく、非常に簡単に使用できます。

于 2017-06-27T13:31:32.103 に答える