python:从url保存图像时出错

python:从url保存图像时出错,python,django,image,jpeg,python-imaging-library,Python,Django,Image,Jpeg,Python Imaging Library,我需要保存从url的图像,与Django。 所以我确实像教程说的那样,但是我得到了一个奇怪的错误 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, ima

我需要保存从url的图像,与Django。 所以我确实像教程说的那样,但是我得到了一个奇怪的错误

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\u image
文件夹,并将其权限设置为777

我的
图像\u内容\u文件
功能:

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)

您能告诉我问题出在哪里吗?

此代码应满足您的需要:

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)

要使其在Python 3中工作,必须使用

urllib.request.urlretrieve(url=filepath)

这绝对与问题无关,为什么?这是python中从url下载文件的方法。如果我知道一个更好的方法来解决一个问题,根据我的说法是相关的。如果你看代码,他正在将他的图片转换为RGB颜色空间,然后保存它。这是错误发生时,而不是他试图下载时。但你是对的,他下载图片的方法很奇怪,用你的方式会更容易。对不起,我的第一条评论写得太快了。你能给我一个保存这张图片的例子吗?foo=urlretrieve(data['image'],'/home/yital9/webservers/binarybits/binarybits/media/upload/article_image/%i.jpg'%article.pk)article.image.save('%i.jpg'%article.pk,foo)--此代码将图像保存在文件夹中,但不要保存到模型对不起,我误解了这个问题,现在检查答案为什么不使用urllib.urlretrieve(“)?