Resize image by 50% using the least amount of lines

Question:

I have the following code that resizes the image by a number hardcoded

I would like it to resize using the following formula – image_size / 2

f = r'C:UserselazarbucketPHOTO'
for file in os.listdir(f):
    f_img = f+"/"+file
    img = Image.open(f_img).resize((540,540)).save(f_img)

Is it possible to shorten this code to fewer lines and instead of using something like 540,540 be able to cut the original size (divide) by 2

I’ve tried following some other formula that I couldn’t fully understand here Open CV Documentation

Asked By: Elazar

||

Answers:

".size" gives the width and height of a picture as a tuple. You can replace the code below with your 4th line.

Image.open(f_img).resize((int(Image.open(f_img).size[0] / 2), int(Image.open(f_img).size[1] / 2))).save(f_img)

However, this one line code is much more inefficient than the code below. It opens the image 3 times instead of one time.

image = Image.open(f_img)
image.resize((int(image.size[0] / 2), int(image.size[1] / 2))).save(f_img)
Answered By: melih akpınar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.