Frame one image within another

Asked

Viewed 32 times

1

I’m having a little trouble implementing the following situation:

  1. Read a folder with multiple images;
  2. I have to read the images and resize each one to 720x185 resolution;

I was able to resize the image as the following code.

from PIL import Image
    
path = 'informe o caminho da imagem'
    
image = Image.open(r"" + path + "")
image = image.resize((720,185))
image.save(path)

However, I have square images where they get distorted, so what I needed to do was this:

  1. Generate a blank image at 720x185 resolution;
  2. Insert the read image in the center of the new created image, respecting only the height. With this, I believe that it would not be distorted;

How can I accomplish this task?

1 answer

1

Sizing with fixed values will not work at all. To keep the ratio you have to do a small calculation.

First you have to take the desired width and divide by the width of the original image, so it will generate value that will be used as multiplier. In sequence, this multiplier will calculate its new height.

For example:

from PIL import Image
    
path = 'informe o caminho da imagem'
image = Image.open(r"" + path + "")

new_width = 720
multiplier = new_width / image.width
new_height = image.height * multiplier
    
image = image.resize((new_width, new_height))
image.save(path)
  • Interesting your idea but my main problem is that the height needs to be 185 or it is necessary to have the width of 720 and height of 185 in some cases in the images I checked they stay with the 720 of width but with a height superior to 185 some idea of how to reverse this situation?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.