Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Resize image by 50% using the least amount of lines

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:\Users\elazar\bucket\PHOTO'
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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

".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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading