Skip to content

Instantly share code, notes, and snippets.

@TimSC
Last active January 15, 2018 02:24
Show Gist options
  • Save TimSC/04bb0f8a3f47f3a1c554 to your computer and use it in GitHub Desktop.
Save TimSC/04bb0f8a3f47f3a1c554 to your computer and use it in GitHub Desktop.
Resize all images in a folder using python and PIL.
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)
@redcpp
Copy link

redcpp commented Jan 15, 2018

After

img = Image.open(fullFi)

this 4 lines of code come handy if for png images

if img.mode in ('RGBA', 'LA'):
            background = Image.new(img.mode[:-1], img.size, '#fff')
            background.paste(img, img.split()[-1])
            img = background

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment