title: Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails
body: <pre><code>import Image
  
  image  = Image.open('images/original.jpg')
  width  = image.size[0]
  height = image.size[1]
  
  if width &gt; height:
      difference = width - height
      offset     = difference / 2
      resize     = (offset, 0, width - offset, height)
  
  else:
      difference = height - width
      offset     = difference / 2
      resize     = (0, offset, width, height - offset)
  
  thumb = image.crop(resize).resize((200, 200), Image.ANTIALIAS)
  thumb.save('thumb.jpg')
  </code></pre>
  
  <p>This is my current thumbnail generation script. The way it works is:</p>
  
  <p>If you have an image that is 400x300 and you want a thumbnail that's 100x100, it will take 50 pixels off the left and right side of the original image. Thus, resizing it to be 300x300. This gives the original image the same aspect ratio as the new thumbnail. After that, it will shrink it down to the required thumbnail size.</p>
  
  <p>The advantages of this is:</p>
  
  <ul>
  <li>The thumbnail is taken from the center of the image</li>
  <li>Aspect ratio doesn't get screwed up</li>
  </ul>
  
  <p>If you were to shrink the 400x300 image down to 100x100, it will look squished. If you took the thumbnail from 0x0 coordinates, you would get the top left of the image. Usually, the focal point of the image is the center.</p>
  
  <p>What I want to be able to do is give the script a width/height of any aspect ratio. For example, if I wanted the 400x300 image to be resized to 400x100, it should shave 150px off the left and right sides of the image...</p>
  
  <p>I can't think of a way to do this. Any ideas?</p>