2

Djangoを使用して、URLから画像を保存する必要があります。だから私はチュートリアルが言うようにしましたが、奇妙なエラーが発生します。

page = requests.get(url)
if page.status_code != 200 or not page.content:
assert 0, 'can\'t download article image'
image = image_content_file(page.content)
article.image.save('%i.jpg' % article.pk, image, save=False)

私の記事モデル:

class Article(models.Model):
   title = models.CharField(max_length=255)
   content = models.TextField(blank=True)
   image = models.ImageField(blank=True, upload_to='upload/article_image')
   date_created = models.DateTimeField(null=True, blank=True, db_index=True)

フォルダを作成upload/article_imageし、その権限を 777 に設定しました

私のimage_content_file機能:

def image_content_file(img_content):
    input_file = StringIO(img_content)
    output_file = StringIO()
    img = Image.open(input_file)
    if img.mode != "RGB":
        img = img.convert("RGB")
    img.save(output_file, "JPEG")
    return ContentFile(output_file.getvalue())

しかし、私はこのエラーが発生します

image = image_content_file(page.content)
  File "/home/yital9/webservers/binarybits/binarybits/../binarybits/utils/img.py", line 24, in image_content_file
    img.save(output_file, "JPEG")
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/local/lib/python2.7/dist-packages/PIL/JpegImagePlugin.py", line 471, in _save
    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
  File "/usr/local/lib/python2.7/dist-packages/PIL/ImageFile.py", line 481, in _save
    e = Image._getencoder(im.mode, e, a, im.encoderconfig)
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 399, in _getencoder
    return apply(encoder, (mode,) + args + extra)
TypeError: function takes at most 9 arguments (11 given)

何が問題なのかアドバイスをいただけますか?

4

2 に答える 2

2

このコードは、必要なことを行う必要があります。

import urllib2
from django.core.files.base import ContentFile

content = ContentFile(urllib2.urlopen(url).read())
article.image.save('%i.jpg' % article.pk, content, save=True)

代わりに、Web から画像をダウンロードするだけの場合は、次のようにすることをお勧めします。

from urllib import urlretrieve
urlretrieve(url, '%i.jpg' % article.pk)
于 2012-10-30T17:35:59.333 に答える
0

Python 3で動作させるには、使用する必要があります

urllib.request.urlretrieve(url=filepath)
于 2021-01-28T12:39:25.000 に答える