Пример #1
0
 def convert(self, mode, *args, **keyw):
     """Converts all layers to a different mode."""
     for layer in self.layers.values():
         if layer.image.mode == mode:
             continue
         if mode == 'P' and imtools.has_alpha(layer.image):
             layer.image = imtools.convert(layer.image, mode, *args, **keyw)
             self.info['transparency'] = 255
         elif mode == 'P':
             layer.image = imtools.convert(layer.image, mode, *args, **keyw)
             self.info['transparency'] = None
         else:
             layer.image = imtools.convert(layer.image, mode, *args, **keyw)
Пример #2
0
def warmup(image, midtone, brighten, amount=100):
    """Apply a toning filter. Move the midtones to the desired
    color while preserving blacks and whites with optional mixing
    with original image - amount: 0-100%"""

    mode = image.mode
    info = image.info

    if image.mode != 'L':
        im = imtools.convert(image, 'L')
    else:
        im = image

    if image.mode != 'RGBA' and imtools.has_transparency(image):
        image = imtools.convert(image, 'RGBA')

    luma = imtools.convert(imtools.split(im)[0], 'F')
    o = []
    m = ImageColor.getrgb(midtone)
    b = brighten / 600.0
    # Calculate channels separately
    for l in range(3):
        o.append(
            ImageMath.eval("m*(255-i)*i+i",
                           i=luma,
                           m=4 * ((m[l] / 255.0) - 0.5 + b) /
                           255.0).convert('L'))

    colorized = Image.merge('RGB', tuple(o))

    if imtools.has_alpha(image):
        imtools.put_alpha(colorized, imtools.get_alpha(image))

    if amount < 100:
        colorized = imtools.blend(image, colorized, amount / 100.0)

    return colorized
Пример #3
0
 def call(self,
          command,
          check_exe=True,
          shell=None,
          size=None,
          unlock=False,
          output_filename=None,
          mode=None):
     if shell is None:
         shell = not system.WINDOWS
     #get command line
     info = self.info
     layer = self.get_layer()
     image = layer.image
     if mode != image.mode:
         image = imtools.convert(image, mode)
     if size != None and size[0] < image.size[0]:
         image = image.copy()
         image.thumbnail(size, Image.ANTIALIAS)
     #loop over input -> save to temp files
     temp_files = []
     done = []
     error = None
     for match in RE_FILE_IN.finditer(command):
         source = match.group()
         if not (source in done):
             ext = match.group(1)
             target = system.TempFile(ext)
             try:
                 imtools.save_safely(image, target.path)
             except Exception, error:
                 pass
             temp_files.append((source, target))
             done.append(source)
             if error:
                 break
Пример #4
0
def make_grid(image,
              grid,
              col_line_width=0,
              row_line_width=0,
              line_color='#FFFFFF',
              line_opacity=0,
              old_size=None,
              scale=True):

    # Check if there is any work to do.
    if grid == (1, 1):
        return image

    # Because of layer support photo size can be different
    # from image layer size
    if old_size is None:
        old_size = image.size

    # Unpack grid
    cols, rows = grid

    # Scaling down?
    if scale:
        # Keep the same number of pixels in the result
        s = sqrt(cols * rows)
        old_size = tuple(map(lambda x: int(x / s), old_size))
        # To scale down we need to make the image processing safe.
        image = imtools.convert_safe_mode(image)\
            .resize(old_size, getattr(Image, 'ANTIALIAS'))

    #displacement
    dx, dy = old_size
    dx += col_line_width
    dy += row_line_width
    new_size = cols * dx - col_line_width, rows * dy - row_line_width

    # The main priority is that the new_canvas has the same mode as the image.

    # Palette images
    if image.mode == 'P':

        if 0 < line_opacity < 255:
            # transparent lines require RGBA
            image = imtools.convert(image, 'RGBA')

        else:
            if 'transparency' in image.info and line_opacity == 0:
                # Make line color transparent for images
                # with transparency.
                line_color_index = image.info['transparency']
                palette = None
            else:
                line_color_index, palette = imtools.fit_color_in_palette(
                    image,
                    ImageColor.getrgb(line_color),
                )
            if line_color_index != -1:
                new_canvas = Image.new('P', new_size, line_color_index)
                imtools.put_palette(new_canvas, image, palette)
            else:
                # Convert to non palette image (RGB or RGBA)
                image = imtools.convert_safe_mode(image)

    # Non palette images
    if image.mode != 'P':

        line_color = ImageColor.getcolor(line_color, image.mode)
        if imtools.has_alpha(image):
            # Make line color transparent for images
            # with an alpha channel.
            line_color = tuple(list(line_color)[:-1] + [line_opacity])
            pass
        new_canvas = Image.new(image.mode, new_size, line_color)

    # Paste grid
    for x in range(cols):
        for y in range(rows):
            pos = (x * dx, y * dy)
            imtools.paste(new_canvas, image, pos, force=True)

    return new_canvas
Пример #5
0
    def call(self,
             command,
             check_exe=True,
             size=None,
             unlock=False,
             output_filename=None,
             mode=None):
        def replace(old, new):
            for i in range(len(command)):
                command[i] = command[i].replace(old, new)

        # ensure command is a list
        if type(command) in types.StringTypes:
            command = shlex.split(command)

        # unpack values
        info = self.info
        layer = self.get_layer()
        image = layer.image

        # adapt image
        if mode != image.mode:
            image = imtools.convert(image, mode)
        if size != None and size[0] < image.size[0]:
            image = image.copy()
            image.thumbnail(size, Image.ANTIALIAS)

        # different image types -> loop over input -> save to temp files
        temp_files = []
        done = []
        error = True
        try:
            for arg in command:
                for match in RE_FILE_IN.finditer(arg):
                    source = match.group()
                    if source in done:
                        continue
                    ext = match.group(1)
                    target = system.TempFile(ext)
                    temp_files.append((source, target))
                    imtools.save_safely(image, target.path)
                    done.append(source)
            error = False
        finally:
            # check if we have a file_in
            # clean up in case of error
            if error:
                for source, target in temp_files:
                    target.close()
        try:
            # loop over output file(s), only one is allowed
            output = None
            index = 0
            for pos, arg in enumerate(command):
                for match in RE_FILE_OUT.finditer(arg):
                    if index > 0:
                        # only 1 is allowed
                        raise Exception('Only one file_out.* is allowed.')
                    source = match.group()
                    ext = match.group(1)
                    output = system.TempFile(ext, output_filename)
                    # fix quotes because of blender action
                    command[pos] = arg.replace(
                        source,
                        system.fix_quotes(output.path),
                    )
                    index += 1

            # tweak command line
            for source, target in temp_files:
                for i in range(len(command)):
                    replace(source, system.fix_quotes(target.path))

            # execute
            stdout, stderr, exit_code = system.call_out_err(command)

            # check if there was output
            if not exit_code:
                if output and not os.path.exists(output.path):
                    no_output = True
                else:
                    no_output = False
        finally:
            # clean up temp files
            for source, target in temp_files:
                target.close()  # = os.remove(target)

        # raise errors if necessary
        if exit_code:
            raise Exception('\n'.join([
                _('Command returned with error "%s":') % exit_code,
                subprocess.list2cmdline(command),
                '',
                'stderr:',
                stderr,
                'stdout:',
                stdout,
            ]))
        if no_output:
            raise Exception('\n'.join([
                _('Command did not produce an output image:'),
                subprocess.list2cmdline(command),
                '',
                'stderr:',
                stderr,
                'stdout:',
                stdout,
            ]))

        # open the output image
        if output:
            layer.open(output.path)
            # DO NOT REMOVE image.load() or output.close will fail on windows
            layer.image.load()
            output.close()