| 130 | |
| 131 | |
| 132 | def minify(basedir, factors=[], resolutions=[]): |
| 133 | needtoload = False |
| 134 | for r in factors: |
| 135 | imgdir = os.path.join(basedir, 'images_{}'.format(r)) |
| 136 | if not os.path.exists(imgdir): |
| 137 | needtoload = True |
| 138 | for r in resolutions: |
| 139 | imgdir = os.path.join(basedir, 'images_{}x{}'.format(r[1], r[0])) |
| 140 | if not os.path.exists(imgdir): |
| 141 | needtoload = True |
| 142 | if not needtoload: |
| 143 | return |
| 144 | |
| 145 | from shutil import copy |
| 146 | from subprocess import check_output |
| 147 | |
| 148 | imgdir = os.path.join(basedir, 'images') |
| 149 | imgs = [os.path.join(imgdir, f) for f in sorted(os.listdir(imgdir))] |
| 150 | imgs = [f for f in imgs if any([f.endswith(ex) for ex in ['JPG', 'jpg', 'png', 'jpeg', 'PNG']])] |
| 151 | imgdir_orig = imgdir |
| 152 | |
| 153 | wd = os.getcwd() |
| 154 | |
| 155 | for r in factors + resolutions: |
| 156 | if isinstance(r, int): |
| 157 | name = 'images_{}'.format(r) |
| 158 | resizearg = '{}%'.format(int(100./r)) |
| 159 | else: |
| 160 | name = 'images_{}x{}'.format(r[1], r[0]) |
| 161 | resizearg = '{}x{}'.format(r[1], r[0]) |
| 162 | imgdir = os.path.join(basedir, name) |
| 163 | if os.path.exists(imgdir): |
| 164 | continue |
| 165 | |
| 166 | print('Minifying', r, basedir) |
| 167 | |
| 168 | os.makedirs(imgdir) |
| 169 | check_output('cp {}/* {}'.format(imgdir_orig, imgdir), shell=True) |
| 170 | |
| 171 | ext = imgs[0].split('.')[-1] |
| 172 | args = ' '.join(['mogrify', '-resize', resizearg, '-format', 'png', '*.{}'.format(ext)]) |
| 173 | print(args) |
| 174 | os.chdir(imgdir) |
| 175 | check_output(args, shell=True) |
| 176 | os.chdir(wd) |
| 177 | |
| 178 | if ext != 'png': |
| 179 | check_output('rm {}/*.{}'.format(imgdir, ext), shell=True) |
| 180 | print('Removed duplicates') |
| 181 | print('Done') |
| 182 | |
| 183 | |
| 184 | |