2016-10-18 38 views
0

我無法保存正在調整大小或直接通過我的admin面板上傳的圖像。我想通過PLP或任何其他方式調整它!如何自動上傳並保存圖像時調整圖像django?

def get_product_image_folder(instance, filename): 

return "static/images/product/%s/base/%s" %(instance.product_id, filename) 
product_image = StringIO.StringIO(i.read()) 
imageImage = Image.open(product_image) 

thumbImage = imageImage.resize((100,100)) 

thumbfile = StringIO() 
thumbImage.save(thumbfile, "JPEG") 

thumbcontent = ContentFile(thumbfile.getvalue()) 

newphoto.thumb.save(filename, thumbcontent) 
new_photo.save() 

回答

0

這可以在模型的save方法,admin的save_model方法或表單的save方法中完成。

我推薦最後一個,因爲它可以讓您從模型和管理界面中分離表單/驗證邏輯。

這可能看起來像以下:

class MyForm(forms.ModelForm): 
    model = MyModel 

    ... 
    def save(self, *args, **options): 
     if self.cleaned_data.get("image_field"): 
      image = self.cleaned_data['image_field'] 
      image = self.resize_image(image) 
      self.cleaned_data['image_field'] = image 
     super(MyForm, self).save(*args, **options) 

    def resize_image(self, image): 
     filepath = image.file.path 
     pil_image = PIL.Image.open(filepath) 
     resized_image = # **similar steps to what you have in your question 
     return resized_image 

您可以把這個新的圖像中的cleaned_data字典,這樣可以節省本身,也可以將其保存到一個新的領域(像「my_field_thumbnail 「)在模型上可編輯= False。

的調整與PIL圖像的實際過程更多信息可以在其他SO問題,如發現: How do I resize an image using PIL and maintain its aspect ratio?