Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python to Resize Images when Greater than 1280 on either side

I want to use Python to resize any image based on the following 2 conditions.

1) If an image is landscape, get width, if greater than 1280 resize image width to 1280 maintaining aspect ratio.

2) If an image is portrait, get height, if greater than1280 resize height to 1280 maintaining aspect ratio.

In Python what is the best package/approach to achieve this? Without knowing what to use this is how I see it working.

Pseudocode:

If image.height > image.width:
  size = image.height

If image.height < image.width:
  size = image.width

If size > 1280:
  resize maintaining aspect ratio

I was looking at Pillow (PIL).

like image 946
Prometheus Avatar asked Feb 11 '15 10:02

Prometheus


People also ask

How do I resize an image without cropping in Python?

just pass the image and mention the size of square you want. explanation: function takes input of any size and it creates a squared shape blank image of size image's height or width whichever is bigger. it then places the original image at the center of the blank image.

How do you proportionally resize an image?

Quickly resize a picture, shape, WordArt, or other object To keep the object's center in the same place, press and hold the OPTION key while you drag the sizing handle. To maintain an object's proportions while resizing it, press and hold the SHIFT key while you drag a corner sizing handle.


1 Answers

You can do it via PIL, something like this:

import Image

MAX_SIZE = 1280
image = Image.open(image_path)
original_size = max(image.size[0], image.size[1])

if original_size >= MAX_SIZE:
    resized_file = open(image_path.split('.')[0] + '_resized.jpg', "w")
    if (image.size[0] > image.size[1]):
        resized_width = MAX_SIZE
        resized_height = int(round((MAX_SIZE/float(image.size[0]))*image.size[1])) 
    else:
        resized_height = MAX_SIZE
        resized_width = int(round((MAX_SIZE/float(image.size[1]))*image.size[0]))

    image = image.resize((resized_width, resized_height), Image.ANTIALIAS)
    image.save(resized_file, 'JPEG')

Additionaly, you can remove original image and rename resized.

like image 200
Eugene Soldatov Avatar answered Nov 14 '22 22:11

Eugene Soldatov