2012-10-30 59 views
1

我需要使用Django從url保存圖片。 所以我確實喜歡這個教程,但是我遇到了一個奇怪的錯誤。python:從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) 

你能告訴我什麼問題嗎?

+0

你爲什麼不使用的urllib .urlretrieve(「http://example.com/img.jpg」)? – mou

回答

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) 

相反,如果你只是想從網上下載的圖像是更好地做到這一點:

from urllib import urlretrieve 
urlretrieve(url, '%i.jpg' % article.pk) 
+0

這與問題完全沒有關係。 – pistache

+0

爲什麼?這是python從url下載文件的方式。如果我知道一個更好的解決問題的方法,那麼根據我的說法,有必要指出。 –

+0

如果您查看代碼,他會將其圖片轉換爲RGB色彩空間,然後將其保存。這是錯誤發生的時間,而不是他嘗試下載時的錯誤。 **但你說得對,他下載圖片的方法很奇怪,用你的方式會更容易**。我寫了我的第一個評論太快了,對不起。 – pistache