From ed0bc9c21f16880840490c91ca3b2b9f598397ab Mon Sep 17 00:00:00 2001 From: hylom Date: Mon, 24 Jun 2013 19:09:13 +0900 Subject: [PATCH] Fix wp_imageswap: when image height is larger than given height, resize to fit given value --- wp_imgswap.py | 44 +++++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/wp_imgswap.py b/wp_imgswap.py index 699862b..d84060c 100644 --- a/wp_imgswap.py +++ b/wp_imgswap.py @@ -14,7 +14,7 @@ import htmltaglib import deterfile import getjpggeom -usage = """usage: %s [link_prefix] [image_width]""" % (os.path.basename(sys.argv[0]),) +usage = """usage: %s [link_prefix] [max_image_width] [max_image_height]""" % (os.path.basename(sys.argv[0]),) rex_imgtag = re.compile(r"""""") rex_atag = re.compile(r"""""") @@ -34,10 +34,14 @@ except IndexError: link_prefix = "" try: - image_width = int(sys.argv[5]) + max_image_width = int(sys.argv[5]) except IndexError: - image_width = 480 + max_image_width = 480 +try: + max_image_height = int(sys.argv[6]) +except IndexError: + max_image_height = 640 def _get_png_geom(filepath): s = filepath.split('.') @@ -67,18 +71,28 @@ def replace_img_tag(line, tagstr, path): attrs = htmltaglib.parse_attributes(tagstr) (root, ext) = os.path.splitext(os.path.basename(path)) + (w, h) = _get_png_geom(path) - filename = "" - if 'width' in attrs: - (w, h) = _get_png_geom(path) - if int(w) > image_width: - attrs['height'] = str(h * image_width / w) - attrs['width'] = str(image_width) - filename = '''%s-%sx%s%s''' % (root, attrs['width'], attrs['height'], ext) - else: - attrs['height'] = str(h) - attrs['width'] = str(w) - filename = '''%s%s''' % (root, ext) + if (w <= max_image_width) and (h <= max_image_height): + # use image as-is. + filename = root + ext + attrs['height'] = str(h) + attrs['width'] = str(w) + else: + # use resized image + new_w = int(w) + new_h = int(h) + if new_w > max_image_width: + new_h = h * max_image_width / w + new_w = max_image_width + print "replace width, %d %d" % (new_w, new_h) + if new_h > max_image_height: + new_h = max_image_height + new_w = w * max_image_height / h + print "replace height, %d %d" % (new_w, new_h) + attrs['height'] = str(new_h) + attrs['width'] = str(new_w) + filename = '''%s-%sx%s%s''' % (root, attrs['width'], attrs['height'], ext) wp_image_url = '''%s%s''' % (image_dir, filename) attrs['src'] = wp_image_url @@ -105,7 +119,7 @@ def replace_a_tag(line, tagstr, path): def replace_figure_tag(line, tagstr, path): attrs = htmltaglib.parse_attributes(tagstr) - width = image_width + width = max_image_width if 'style' in attrs: m = re.search(ur'width:\s*([0-9]+)px', attrs['style']) if m: -- 2.11.0