Skip to content
Myr

imagepipe.py

This file

Path

examples/imagepipe/imagepipe.py

288 lines · 8.1 KiB · Python

Last changed by

Merge pull request #1848 from pallets/rename-result-callbackDavid Lordbefore adoption0dc6d74

History of this file

Take it

1from functools import update_wrapper23from PIL import Image4from PIL import ImageEnhance5from PIL import ImageFilter67import click8910@click.group(chain=True)11def cli():12    """This script processes a bunch of images through pillow in a unix13    pipe.  One commands feeds into the next.1415    Example:1617    \b18        imagepipe open -i example01.jpg resize -w 128 display19        imagepipe open -i example02.jpg blur save20    """212223@cli.result_callback()24def process_commands(processors):25    """This result callback is invoked with an iterable of all the chained26    subcommands.  As in this example each subcommand returns a function27    we can chain them together to feed one into the other, similar to how28    a pipe on unix works.29    """30    # Start with an empty iterable.31    stream = ()3233    # Pipe it through all stream processors.34    for processor in processors:35        stream = processor(stream)3637    # Evaluate the stream and throw away the items.38    for _ in stream:39        pass404142def processor(f):43    """Helper decorator to rewrite a function so that it returns another44    function from it.45    """4647    def new_func(*args, **kwargs):48        def processor(stream):49            return f(stream, *args, **kwargs)5051        return processor5253    return update_wrapper(new_func, f)545556def generator(f):57    """Similar to the :func:`processor` but passes through old values58    unchanged and does not pass through the values as parameter.59    """6061    @processor62    def new_func(stream, *args, **kwargs):63        yield from stream64        yield from f(*args, **kwargs)6566    return update_wrapper(new_func, f)676869def copy_filename(new, old):70    new.filename = old.filename71    return new727374@cli.command("open")75@click.option(76    "-i",77    "--image",78    "images",79    type=click.Path(),80    multiple=True,81    help="The image file to open.",82)83@generator84def open_cmd(images):85    """Loads one or multiple images for processing.  The input parameter86    can be specified multiple times to load more than one image.87    """88    for image in images:89        try:90            click.echo(f"Opening '{image}'")91            if image == "-":92                img = Image.open(click.get_binary_stdin())93                img.filename = "-"94            else:95                img = Image.open(image)96            yield img97        except Exception as e:98            click.echo(f"Could not open image '{image}': {e}", err=True)99100101@cli.command("save")102@click.option(103    "--filename",104    default="processed-{:04}.png",105    type=click.Path(),106    help="The format for the filename.",107    show_default=True,108)109@processor110def save_cmd(images, filename):111    """Saves all processed images to a series of files."""112    for idx, image in enumerate(images):113        try:114            fn = filename.format(idx + 1)115            click.echo(f"Saving '{image.filename}' as '{fn}'")116            yield image.save(fn)117        except Exception as e:118            click.echo(f"Could not save image '{image.filename}': {e}", err=True)119120121@cli.command("display")122@processor123def display_cmd(images):124    """Opens all images in an image viewer."""125    for image in images:126        click.echo(f"Displaying '{image.filename}'")127        image.show()128        yield image129130131@cli.command("resize")132@click.option("-w", "--width", type=int, help="The new width of the image.")133@click.option("-h", "--height", type=int, help="The new height of the image.")134@processor135def resize_cmd(images, width, height):136    """Resizes an image by fitting it into the box without changing137    the aspect ratio.138    """139    for image in images:140        w, h = (width or image.size[0], height or image.size[1])141        click.echo(f"Resizing '{image.filename}' to {w}x{h}")142        image.thumbnail((w, h))143        yield image144145146@cli.command("crop")147@click.option(148    "-b", "--border", type=int, help="Crop the image from all sides by this amount."149)150@processor151def crop_cmd(images, border):152    """Crops an image from all edges."""153    for image in images:154        box = [0, 0, image.size[0], image.size[1]]155156        if border is not None:157            for idx, val in enumerate(box):158                box[idx] = max(0, val - border)159            click.echo(f"Cropping '{image.filename}' by {border}px")160            yield copy_filename(image.crop(box), image)161        else:162            yield image163164165def convert_rotation(ctx, param, value):166    if value is None:167        return168    value = value.lower()169    if value in ("90", "r", "right"):170        return (Image.ROTATE_90, 90)171    if value in ("180", "-180"):172        return (Image.ROTATE_180, 180)173    if value in ("-90", "270", "l", "left"):174        return (Image.ROTATE_270, 270)175    raise click.BadParameter(f"invalid rotation '{value}'")176177178def convert_flip(ctx, param, value):179    if value is None:180        return181    value = value.lower()182    if value in ("lr", "leftright"):183        return (Image.FLIP_LEFT_RIGHT, "left to right")184    if value in ("tb", "topbottom", "upsidedown", "ud"):185        return (Image.FLIP_LEFT_RIGHT, "top to bottom")186    raise click.BadParameter(f"invalid flip '{value}'")187188189@cli.command("transpose")190@click.option(191    "-r", "--rotate", callback=convert_rotation, help="Rotates the image (in degrees)"192)193@click.option("-f", "--flip", callback=convert_flip, help="Flips the image  [LR / TB]")194@processor195def transpose_cmd(images, rotate, flip):196    """Transposes an image by either rotating or flipping it."""197    for image in images:198        if rotate is not None:199            mode, degrees = rotate200            click.echo(f"Rotate '{image.filename}' by {degrees}deg")201            image = copy_filename(image.transpose(mode), image)202        if flip is not None:203            mode, direction = flip204            click.echo(f"Flip '{image.filename}' {direction}")205            image = copy_filename(image.transpose(mode), image)206        yield image207208209@cli.command("blur")210@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")211@processor212def blur_cmd(images, radius):213    """Applies gaussian blur."""214    blur = ImageFilter.GaussianBlur(radius)215    for image in images:216        click.echo(f"Blurring '{image.filename}' by {radius}px")217        yield copy_filename(image.filter(blur), image)218219220@cli.command("smoothen")221@click.option(222    "-i",223    "--iterations",224    default=1,225    show_default=True,226    help="How many iterations of the smoothen filter to run.",227)228@processor229def smoothen_cmd(images, iterations):230    """Applies a smoothening filter."""231    for image in images:232        click.echo(233            f"Smoothening {image.filename!r} {iterations}"234            f" time{'s' if iterations != 1 else ''}"235        )236        for _ in range(iterations):237            image = copy_filename(image.filter(ImageFilter.BLUR), image)238        yield image239240241@cli.command("emboss")242@processor243def emboss_cmd(images):244    """Embosses an image."""245    for image in images:246        click.echo(f"Embossing '{image.filename}'")247        yield copy_filename(image.filter(ImageFilter.EMBOSS), image)248249250@cli.command("sharpen")251@click.option(252    "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True253)254@processor255def sharpen_cmd(images, factor):256    """Sharpens an image."""257    for image in images:258        click.echo(f"Sharpen '{image.filename}' by {factor}")259        enhancer = ImageEnhance.Sharpness(image)260        yield copy_filename(enhancer.enhance(max(1.0, factor)), image)261262263@cli.command("paste")264@click.option("-l", "--left", default=0, help="Offset from left.")265@click.option("-r", "--right", default=0, help="Offset from right.")266@processor267def paste_cmd(images, left, right):268    """Pastes the second image on the first image and leaves the rest269    unchanged.270    """271    imageiter = iter(images)272    image = next(imageiter, None)273    to_paste = next(imageiter, None)274275    if to_paste is None:276        if image is not None:277            yield image278        return279280    click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")281    mask = None282    if to_paste.mode == "RGBA" or "transparency" in to_paste.info:283        mask = to_paste284    image.paste(to_paste, (left, right), mask)285    image.filename += f"+{to_paste.filename}"286    yield image287288    yield from imageiter