2016-02-26 43 views
3

Django中有一個ImageFieldFile類型的圖像。如果我做print type(image),我得到<class 'django.db.models.fields.files.ImageFieldFile'>在Django中更改圖像類型

接下來,我打開這個使用PIL的Image.open(image),通過image.resize((20,20))調整並關閉它image.close()

關閉之後,我發現圖片的類型已更改爲<class 'PIL.Image.Image'>

如何將其更改回<class 'django.db.models.fields.files.ImageFieldFile'>?我認爲.close()就足夠了。

+0

你爲什麼需要改回來?這裏有更大的問題嗎? –

+0

將它保存在Azure存儲blob上,我一直在爲''獲取一個類型錯誤,但對於'' –

+0

這可能不會有太大的幫助,但檢查一些編輯圖像的方式,而上傳http://stackoverflow.com/questions/15519716/django-resize-image-during-upload和http://stackoverflow.com/questions/24373341/django-image-resizing-and-convert-before-upload –

回答

1

我解決這個問題的方法是將它保存到一個BytesIO對象,然後將其填入InMemoryUploadedFile。所以像這樣:

from io import BytesIO 
from PIL import Image 
from django.core.files.uploadedfile import InMemoryUploadedFile 

# Where image is your ImageFieldFile 
pil_image = Image.open(image) 
pil_image.resize((20, 20)) 

image_bytes = BytesIO() 
pil_image.save(image_bytes) 

new_image = InMemoryUploadedFile(
    image_bytes, None, image.name, image.type, None, None, None 
) 
image_bytes.close() 

不是非常優雅,但它完成了工作。這是在Python 3中完成的。不確定是否兼容Python 2。

編輯:

實際上,在事後,I like this answer better。希望它存在,當我試圖解決這個問題。 : - \

希望這會有所幫助。乾杯!