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 fileTake it
The walk stopped after 200 commits: lines older than a438322 point at it.
Merge branch '7.x'David Lordbefore adoptiona438322
lines 1–2why, one step back1from functools import update_wrapper2Merge branch '7.x'David Lordbefore adoption7239794
lines 3–5why, one step back3from PIL import Image4from PIL import ImageEnhance5from PIL import ImageFilterMerge branch '7.x'David Lordbefore adoptiona438322
line 6why, one step back6Merge branch '7.x'David Lordbefore adoption7239794
lines 7–9why, one step back7import click89Merge branch '7.x'David Lordbefore adoptiona438322
lines 10–22why, one step back10@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 """2122Merge pull request #1848 from pallets/rename-result-callbackDavid Lordbefore adoption0dc6d74
line 23why, one step back23@cli.result_callback()Merge branch '7.x'David Lordbefore adoptiona438322
lines 24–45why, one step back24def 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 """Merge branch '7.x'David Lordbefore adoption7239794
line 46why, one step back46Merge branch '7.x'David Lordbefore adoptiona438322
lines 47–49why, one step back47 def new_func(*args, **kwargs):48 def processor(stream):49 return f(stream, *args, **kwargs)Merge branch '7.x'David Lordbefore adoption7239794
line 50why, one step back50Merge branch '7.x'David Lordbefore adoptiona438322
line 51why, one step back51 return processorMerge branch '7.x'David Lordbefore adoption7239794
line 52why, one step back52Merge branch '7.x'David Lordbefore adoptiona438322
lines 53–59why, one step back53 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 """Merge branch '7.x'David Lordbefore adoption7239794
line 60why, one step back60Merge branch '7.x'David Lordbefore adoptiona438322
lines 61–62why, one step back61 @processor62 def new_func(stream, *args, **kwargs):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 63–64why, one step back63 yield from stream64 yield from f(*args, **kwargs)Merge branch '7.x'David Lordbefore adoption7239794
line 65why, one step back65Merge branch '7.x'David Lordbefore adoptiona438322
lines 66–73why, one step back66 return update_wrapper(new_func, f)676869def copy_filename(new, old):70 new.filename = old.filename71 return new7273Merge branch '7.x'David Lordbefore adoption7239794
lines 74–82why, one step back74@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)Merge branch '7.x'David Lordbefore adoptiona438322
lines 83–89why, one step back83@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:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 90why, one step back90 click.echo(f"Opening '{image}'")Merge branch '7.x'David Lordbefore adoption7239794
line 91why, one step back91 if image == "-":Merge branch '7.x'David Lordbefore adoptiona438322
line 92why, one step back92 img = Image.open(click.get_binary_stdin())Merge branch '7.x'David Lordbefore adoption7239794
line 93why, one step back93 img.filename = "-"Merge branch '7.x'David Lordbefore adoptiona438322
lines 94–97why, one step back94 else:95 img = Image.open(image)96 yield img97 except Exception as e:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 98why, one step back98 click.echo(f"Could not open image '{image}': {e}", err=True)Merge branch '7.x'David Lordbefore adoptiona438322
lines 99–100why, one step back99100Merge branch '7.x'David Lordbefore adoption7239794
lines 101–108why, one step back101@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)Merge branch '7.x'David Lordbefore adoptiona438322
lines 109–113why, one step back109@processor110def save_cmd(images, filename):111 """Saves all processed images to a series of files."""112 for idx, image in enumerate(images):113 try:Merge branch '7.x'David Lordbefore adoption7239794
line 114why, one step back114 fn = filename.format(idx + 1)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 115why, one step back115 click.echo(f"Saving '{image.filename}' as '{fn}'")Merge branch '7.x'David Lordbefore adoptiona438322
lines 116–117why, one step back116 yield image.save(fn)117 except Exception as e:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 118why, one step back118 click.echo(f"Could not save image '{image.filename}': {e}", err=True)Merge branch '7.x'David Lordbefore adoptiona438322
lines 119–120why, one step back119120Merge branch '7.x'David Lordbefore adoption7239794
line 121why, one step back121@cli.command("display")Merge branch '7.x'David Lordbefore adoptiona438322
lines 122–125why, one step back122@processor123def display_cmd(images):124 """Opens all images in an image viewer."""125 for image in images:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 126why, one step back126 click.echo(f"Displaying '{image.filename}'")Merge branch '7.x'David Lordbefore adoptiona438322
lines 127–130why, one step back127 image.show()128 yield image129130Merge branch '7.x'David Lordbefore adoption7239794
lines 131–133why, one step back131@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.")Merge branch '7.x'David Lordbefore adoptiona438322
lines 134–140why, one step back134@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])Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 141why, one step back141 click.echo(f"Resizing '{image.filename}' to {w}x{h}")Merge branch '7.x'David Lordbefore adoptiona438322
lines 142–145why, one step back142 image.thumbnail((w, h))143 yield image144145Merge branch '7.x'David Lordbefore adoption7239794
lines 146–149why, one step back146@cli.command("crop")147@click.option(148 "-b", "--border", type=int, help="Crop the image from all sides by this amount."149)Merge branch '7.x'David Lordbefore adoptiona438322
lines 150–158why, one step back150@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)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 159why, one step back159 click.echo(f"Cropping '{image.filename}' by {border}px")Merge branch '7.x'David Lordbefore adoptiona438322
lines 160–168why, one step back160 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()Merge branch '7.x'David Lordbefore adoption7239794
line 169why, one step back169 if value in ("90", "r", "right"):Merge branch '7.x'David Lordbefore adoptiona438322
line 170why, one step back170 return (Image.ROTATE_90, 90)Merge branch '7.x'David Lordbefore adoption7239794
line 171why, one step back171 if value in ("180", "-180"):Merge branch '7.x'David Lordbefore adoptiona438322
line 172why, one step back172 return (Image.ROTATE_180, 180)Merge branch '7.x'David Lordbefore adoption7239794
line 173why, one step back173 if value in ("-90", "270", "l", "left"):Merge branch '7.x'David Lordbefore adoptiona438322
line 174why, one step back174 return (Image.ROTATE_270, 270)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 175why, one step back175 raise click.BadParameter(f"invalid rotation '{value}'")Merge branch '7.x'David Lordbefore adoptiona438322
lines 176–181why, one step back176177178def convert_flip(ctx, param, value):179 if value is None:180 return181 value = value.lower()Merge branch '7.x'David Lordbefore adoption7239794
lines 182–185why, one step back182 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")Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 186why, one step back186 raise click.BadParameter(f"invalid flip '{value}'")Merge branch '7.x'David Lordbefore adoptiona438322
lines 187–188why, one step back187188Merge branch '7.x'David Lordbefore adoption7239794
lines 189–193why, one step back189@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]")Merge branch '7.x'David Lordbefore adoptiona438322
lines 194–199why, one step back194@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 = rotateMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 200why, one step back200 click.echo(f"Rotate '{image.filename}' by {degrees}deg")Merge branch '7.x'David Lordbefore adoptiona438322
lines 201–203why, one step back201 image = copy_filename(image.transpose(mode), image)202 if flip is not None:203 mode, direction = flipMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 204why, one step back204 click.echo(f"Flip '{image.filename}' {direction}")Merge branch '7.x'David Lordbefore adoptiona438322
lines 205–208why, one step back205 image = copy_filename(image.transpose(mode), image)206 yield image207208Merge branch '7.x'David Lordbefore adoption7239794
lines 209–210why, one step back209@cli.command("blur")210@click.option("-r", "--radius", default=2, show_default=True, help="The blur radius.")Merge branch '7.x'David Lordbefore adoptiona438322
lines 211–215why, one step back211@processor212def blur_cmd(images, radius):213 """Applies gaussian blur."""214 blur = ImageFilter.GaussianBlur(radius)215 for image in images:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 216why, one step back216 click.echo(f"Blurring '{image.filename}' by {radius}px")Merge branch '7.x'David Lordbefore adoptiona438322
lines 217–219why, one step back217 yield copy_filename(image.filter(blur), image)218219Merge branch '7.x'David Lordbefore adoption7239794
lines 220–227why, one step back220@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)Merge branch '7.x'David Lordbefore adoptiona438322
lines 228–231why, one step back228@processor229def smoothen_cmd(images, iterations):230 """Applies a smoothening filter."""231 for image in images:Merge branch '7.x'David Lordbefore adoption7239794
line 232why, one step back232 click.echo(Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 233–234why, one step back233 f"Smoothening {image.filename!r} {iterations}"234 f" time{'s' if iterations != 1 else ''}"Merge branch '7.x'David Lordbefore adoption7239794
lines 235–236why, one step back235 )236 for _ in range(iterations):Merge branch '7.x'David Lordbefore adoptiona438322
lines 237–240why, one step back237 image = copy_filename(image.filter(ImageFilter.BLUR), image)238 yield image239240Merge branch '7.x'David Lordbefore adoption7239794
line 241why, one step back241@cli.command("emboss")Merge branch '7.x'David Lordbefore adoptiona438322
lines 242–245why, one step back242@processor243def emboss_cmd(images):244 """Embosses an image."""245 for image in images:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 246why, one step back246 click.echo(f"Embossing '{image.filename}'")Merge branch '7.x'David Lordbefore adoptiona438322
lines 247–249why, one step back247 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)248249Merge branch '7.x'David Lordbefore adoption7239794
lines 250–253why, one step back250@cli.command("sharpen")251@click.option(252 "-f", "--factor", default=2.0, help="Sharpens the image.", show_default=True253)Merge branch '7.x'David Lordbefore adoptiona438322
lines 254–257why, one step back254@processor255def sharpen_cmd(images, factor):256 """Sharpens an image."""257 for image in images:Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 258why, one step back258 click.echo(f"Sharpen '{image.filename}' by {factor}")Merge branch '7.x'David Lordbefore adoptiona438322
lines 259–262why, one step back259 enhancer = ImageEnhance.Sharpness(image)260 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)261262Merge branch '7.x'David Lordbefore adoption7239794
lines 263–265why, one step back263@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.")Merge branch '7.x'David Lordbefore adoptiona438322
lines 266–279why, one step back266@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 return279Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 280why, one step back280 click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")Merge branch '7.x'David Lordbefore adoptiona438322
line 281why, one step back281 mask = NoneMerge branch '7.x'David Lordbefore adoption7239794
line 282why, one step back282 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:Merge branch '7.x'David Lordbefore adoptiona438322
lines 283–284why, one step back283 mask = to_paste284 image.paste(to_paste, (left, right), mask)Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 285why, one step back285 image.filename += f"+{to_paste.filename}"Merge branch '7.x'David Lordbefore adoptiona438322
lines 286–287why, one step back286 yield image287Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 288why, one step back288 yield from imageiter