Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize images in directory

I have a directory full of images that I would like to resize to around 60% of their original size.

How would I go about doing this? Can be in either Python or Perl

Cheers

Eef

like image 632
RailsSon Avatar asked Jun 26 '09 11:06

RailsSon


1 Answers

If you want to do it programatically, which I assume is the case, use PIL to resize e.g.

newIm = im.resize((newW, newH)

then save it to same file or a new location.

Go through the folder recursively and apply resize function to all images.

I have come up with a sample script which I think will work for you. You can improve on it: Maybe make it graphical, add more options e.g. same extension or may be all png, resize sampling linear/bilinear etc

import os
import sys
from PIL import Image

def resize(folder, fileName, factor):
    filePath = os.path.join(folder, fileName)
    im = Image.open(filePath)
    w, h  = im.size
    newIm = im.resize((int(w*factor), int(h*factor)))
    # i am saving a copy, you can overrider orginal, or save to other folder
    newIm.save(filePath+"copy.png")

def bulkResize(imageFolder, factor):
    imgExts = ["png", "bmp", "jpg"]
    for path, dirs, files in os.walk(imageFolder):
        for fileName in files:
            ext = fileName[-3:].lower()
            if ext not in imgExts:
                continue

            resize(path, fileName, factor)

if __name__ == "__main__":
    imageFolder=sys.argv[1] # first arg is path to image folder
    resizeFactor=float(sys.argv[2])/100.0# 2nd is resize in %
    bulkResize(imageFolder, resizeFactor)
like image 166
Anurag Uniyal Avatar answered Oct 21 '22 10:10

Anurag Uniyal