2017-05-02 1 views
1

기본적으로 thumbnail 방법은 일관되게 크기가 축소판이 될 수있는 종횡비를 유지합니다.베개는 가로 세로 비율을 보존하는 대신 자르기로 축소판을 만듭니다.

Image.thumbnail (크기, resample = 3) 이미지를 미리보기 이미지로 만듭니다. 이 메서드는 지정된 크기보다 크지 않은 이미지의 축소판 버전을 포함하도록 이미지를 수정합니다. 이 메서드는 적절한 축소판 크기를 계산하여 이미지의 모양을 유지하고, draft() 메서드를 호출하여 파일 판독기를 구성하고 (적용 가능한 경우) 마지막으로 이미지의 크기를 조정합니다.

제공되는 전체 캔버스가 채워지도록 이미지를 자르려면 이미지를 뒤틀 지 말아야합니다. 예를 들어 640 x 480 크기의 이미지에서 Image.thumbnail((200, 200), Image.ANTIALIAS)은 480x480 크기로 자른 다음 정확하게 200x200 (199 또는 201이 아님)로 확대됩니다. 어떻게 할 수 있습니까?

답변

1

이것은 두 단계로 수행하는 것이 가장 쉽습니다. 먼저 자르기를 수행 한 다음 축소판을 생성합니다. 주어진 가로 세로 비율로 잘라내 기는 일반적으로 충분하지만 필로우에서는 실제로 그 기능이 있어야합니다.하지만 내가 아는 한 실제로는 없습니다. 다음은 간단한 구현, 이미지 클래스에 원숭이 패치 : 당신이 Image.Image.crop_to_aspect = _Image.crop_to_aspect`, 왜`사용하는 이유는 무엇입니까

from PIL import Image 

class _Image(Image.Image): 

    def crop_to_aspect(self, aspect, divisor=1, alignx=0.5, aligny=0.5): 
     """Crops an image to a given aspect ratio. 
     Args: 
      aspect (float): The desired aspect ratio. 
      divisor (float): Optional divisor. Allows passing in (w, h) pair as the first two arguments. 
      alignx (float): Horizontal crop alignment from 0 (left) to 1 (right) 
      aligny (float): Vertical crop alignment from 0 (left) to 1 (right) 
     Returns: 
      Image: The cropped Image object. 
     """ 
     if self.width/self.height > aspect/divisor: 
      newwidth = int(self.height * (aspect/divisor)) 
      newheight = self.height 
     else: 
      newwidth = self.width 
      newheight = int(self.width/(aspect/divisor)) 
     img = self.crop((alignx * (self.width - newwidth), 
         aligny * (self.height - newheight), 
         alignx * (self.width - newwidth) + newwidth, 
         aligny * (self.height - newheight) + newheight)) 
     return img 

Image.Image.crop_to_aspect = _Image.crop_to_aspect 

이를 감안할 때, 당신은 단지

cropped = img.crop_to_aspect(200,200) 
cropped.thumbnail((200, 200), Image.ANTIALIAS) 
+0

을 쓸 수 있습니다 'Image.Image'를 상속하지 않고 새로운 클래스를 사용합니까? – dtgq

+1

베개에서 이미지를 만드는 표준 방법은 이미지 모듈 (open(), new() 등)의 팩토리 함수를 사용하기 때문에 항상'Image' 객체를 만듭니다. 그래도 좋은 결과를 얻을 수있는 방법이 있습니다. –

관련 문제