Skip to content

Instantly share code, notes, and snippets.

@falsetru
Created March 9, 2011 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save falsetru/861947 to your computer and use it in GitHub Desktop.
Save falsetru/861947 to your computer and use it in GitHub Desktop.
make half-size version of images. (a.png -> a.png(/2), a@2x.png(original))
import Image
import os
import shutil
import math
def half(size):
return int(math.ceil(size / 2.0))
class Candidate(str):
SUFFIX = '@2x.png'
@property
def filename_for_double_size(self):
return self[:-4] + self.SUFFIX
def is_target(self):
if not self.endswith('.png'):
return False
if self.endswith(self.SUFFIX):
return False
if os.path.exists(self.filename_for_double_size):
return False
return True
def copy2x(self):
shutil.copy(self, self.filename_for_double_size)
def reduce_inplace(self):
im = Image.open(self)
size = im.size
newsize = map(half, size)
im = im.resize(newsize)
im.save(self)
return size, newsize
for p, ds, fs in os.walk('.'):
for fn in fs:
candidate = Candidate(os.path.join(p, fn))
if candidate.is_target():
print candidate
candidate.copy2x()
size, newsize = candidate.reduce_inplace()
print ' {0[0]:4}x{0[1]:4} -> {1[0]:4}x{1[1]:4}'.format(size, newsize)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment