title: Python3: Resize rectangular image to a different kind of rectangle, keeping ratio and fill background with black
body: <p>I have a very similar question to this: <a href="https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black?rq=1">Resize rectangular image to square, keeping ratio and fill background with black</a>, but I would like to resize to a nonsquare image and center the image either horizontally or vertically if needed.</p>
  
  <p>Here are some examples of desired outputs. I made this image entirely with Paint, so the images might not actually be perfectly centered, but centering is what I'd like to achieve:</p>
  
  <p><a href="https://i.stack.imgur.com/I04tA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I04tA.png" alt="desired outputs"></a></p>
  
  <p>I tried the following code that I edited from the question linked:</p>
  
  <pre><code>def fix_size(fn, desired_w=256, desired_h=256, fill_color=(0, 0, 0, 255)):
      """Edited from https://stackoverflow.com/questions/44231209/resize-rectangular-image-to-square-keeping-ratio-and-fill-background-with-black"""
      im = Image.open(fn)
      x, y = im.size
      #size = max(min_size, x, y)
      w = max(desired_w, x)
      h = max(desired_h, y)
      new_im = Image.new('RGBA', (w, h), fill_color)
      new_im.paste(im, ((w - x) // 2, (h - y) // 2))
      return new_im.resize((desired_w, desired_h))
  </code></pre>
  
  <p>That doesn't work however as it still stretches some images into square shaped ones (at least the image b in the example. What comes to big images, it seems to rotate them instead!</p>