sphinx_nbexamples/__init__.py
def scale_image(self, in_fname, out_fname, max_width, max_height):
        """Scales an image with the same aspect ratio centered in an
           image with a given max_width and max_height
           if in_fname == out_fname the image can only be scaled down
        """
        # local import to avoid testing dependency on PIL:
        try:
            from PIL import Image
        except ImportError:
            import Image
        img = Image.open(in_fname)
        width_in, height_in = img.size
        scale_w = max_width / float(width_in)
        scale_h = max_height / float(height_in)

        if height_in * scale_w <= max_height:
            scale = scale_w
        else:
            scale = scale_h

        if scale >= 1.0 and in_fname == out_fname:
            return

        width_sc = int(round(scale * width_in))
        height_sc = int(round(scale * height_in))

        # resize the image
        img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

        # insert centered
        thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))
        pos_insert = (
            (max_width - width_sc) // 2, (max_height - height_sc) // 2)
        thumb.paste(img, pos_insert)

        thumb.save(out_fname)
def scale_image(self, in_fname, out_fname, max_width, max_height):
        """Scales an image with the same aspect ratio centered in an
           image with a given max_width and max_height
           if in_fname == out_fname the image can only be scaled down
        """
        # local import to avoid testing dependency on PIL:
        try:
            from PIL import Image
        except ImportError:
            import Image
        img = Image.open(in_fname)
        width_in, height_in = img.size
        scale_w = max_width / float(width_in)
        scale_h = max_height / float(height_in)

        if height_in * scale_w <= max_height:
            scale = scale_w
        else:
            scale = scale_h

        if scale >= 1.0 and in_fname == out_fname:
            return

        width_sc = int(round(scale * width_in))
        height_sc = int(round(scale * height_in))

        # resize the image
        img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)

        # insert centered
        thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))
        pos_insert = (
            (max_width - width_sc) // 2, (max_height - height_sc) // 2)
        thumb.paste(img, pos_insert)

        thumb.save(out_fname)
Scales an image with the same aspect ratio centered in an
           image with a given max_width and max_height
           if in_fname == out_fname the image can only be scaled down