[英]django-cumulus: retrieve PIL.Image object from django.db.models.ImageField
[英]How can I programatically save an Image to an ImageField using Django-Cumulus?
我正在使用Django-Cumulus將圖像存儲到Rackspace的Cloudfiles平台。
我想動態地處理圖像並將其另存為模型的新ImageField。 例如,我有一個具有以下ImageField的照片模型:image,thumb_256x256
在我的Form的save()方法中,我讓用戶指定裁剪位置(使用JCrop)。
無論如何,我知道如何獲取用戶上傳的現有圖像文件。 我也知道如何使用PIL進行操作。 我遇到的問題是創建一個新的Rackspace文件並對其進行寫入。
我不斷收到異常“ NoSuchObject”。
這是一些示例代碼:
def save(self, commit=True):
""" Override the Save method to create a thumbnail of the image. """
m = super(PhotoUpdateForm, self).save(commit=False)
image = Image.open(m.image.file)
image.thumbnail((256,256), Image.ANTIALIAS)
thumb_io = CloudFilesStorageFile(storage=CLOUDFILES_STORAGE, name='foo/bar/test.jpg')
image.save(thumb_io.file, format='JPEG')
此外,一旦到達這一點,將圖像設置為模型的另一個ImageField的最佳方法是什么? (在我的情況下為m.thumb_256x256)
提前致謝!
更新:我正在使用的實際Cloudfiles Django應用程序的名稱為“ django-cumulus ”
這是一個臨時解決方案。 我在正確設置新文件名時遇到問題。 它只是在文件名后附加_X。 因此,例如,每當我保存新版本時,somefilename.jpg就會變成somefilename_1.jpg。
這段代碼有點難看,但是確實可以完成工作。 它會創建圖像的裁剪版本,並在需要時生成縮略圖。
def save(self, commit=True):
""" Override the Save method to create a thumbnail of the image. """
m = super(PhotoUpdateForm, self).save(commit=False)
# Cropped Version
if set(('x1', 'x2', 'y1', 'y2')) <= set(self.cleaned_data):
box = int(self.cleaned_data['x1']), \
int(self.cleaned_data['y1']), \
int(self.cleaned_data['x2']), \
int(self.cleaned_data['y2'])
image = Image.open(m.image.file)
image = image.crop(box)
temp_file = NamedTemporaryFile(delete=True)
image.save(temp_file, format="JPEG")
m.image.save("image.jpg", File(temp_file))
cropped = True # Let's rebuild the thumbnail
# 256x256 Thumbnail
if not m.thumb_256x256 or cropped:
if not image:
image = Image.open(m.image.file)
image.thumbnail((256,256), Image.ANTIALIAS)
temp_file = NamedTemporaryFile(delete=True)
image.save(temp_file, format="JPEG")
m.thumb_256x256.save("thumbnail.jpg", File(temp_file))
if commit: m.save()
return m
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.