Last active
January 15, 2018 02:24
-
-
Save TimSC/04bb0f8a3f47f3a1c554 to your computer and use it in GitHub Desktop.
Resize all images in a folder using python and PIL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os, sys | |
| from PIL import Image | |
| if __name__ == "__main__": | |
| fiList = os.listdir(sys.argv[1]) | |
| fiList = fiList[:] | |
| fiList.sort() | |
| if len(sys.argv) < 3: | |
| print "Usage: {0} /src/folder /dest/folder [target-size]".format(sys.argv[0]) | |
| exit() | |
| if sys.argv[1] == sys.argv[2]: | |
| print "Source and destination may not be the same" | |
| exit() | |
| targetSize = 1024. * 2. | |
| if len(sys.argv) >= 4: | |
| targetSize = float(sys.argv[3]) | |
| for fi in fiList: | |
| fullFi = os.path.join(sys.argv[1],fi) | |
| outFullFi = os.path.join(sys.argv[2],fi) | |
| if not os.path.isfile(fullFi): | |
| continue | |
| print "in ", fullFi | |
| img = Image.open(fullFi) | |
| #print img.size | |
| scale1 = targetSize / img.size[0] | |
| scale2 = targetSize / img.size[1] | |
| scale = min(scale1, scale2) | |
| resizedDim = (img.size[0] * scale, img.size[1] * scale) | |
| resizedDim = map(round, resizedDim) | |
| resizedDim = map(int, resizedDim) | |
| rimg = img.resize(resizedDim) | |
| #print rimg.size | |
| print "out", outFullFi | |
| rimg.save(outFullFi) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After
this 4 lines of code come handy if for png images