2016-10-18 6 views
0

크기가 조정되거나 내 admin 패널을 통해 직접 업로드하는 이미지를 저장할 수 없습니다. PLP 또는 다른 방법으로 크기를 조정하고 싶습니다!업로드하는 동안 이미지의 크기를 조정하고 자동으로 장고를 저장하는 방법?

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 메소드에서 수행 할 수 있습니다.

모델 및 관리 인터페이스에서 양식/유효성 검증 로직을 분리 할 수 ​​있으므로 마지막으로 권장합니다. "my_field_thumbnail 같은

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 사전에이 새로운 이미지를 넣을 수 있습니다, 또는 당신이 새로운 분야에 저장할 수 있습니다 (문제 :

여기에는 다음과 같은 것을 볼 수 있었다 ") 모델에서 편집 가능 = False입니다.

PIL로 이미지 크기를 조정의 실제 프로세스에

더 많은 정보는 다른 SO 질문, 예에서 찾아 볼 수있다 : How do I resize an image using PIL and maintain its aspect ratio?

관련 문제