Ejemplo n.º 1
0
def pgmagick_scale_plus_sharpen(filename, width, height):
    im = pgmagick.Image(pgmagick.Blob(open(filename).read()),
                        pgmagick.Geometry(width, height))
    im.scale('%dx%d' % (width, height))
    im.sharpen(1)
    im.quality(95)
    im.write('outpgsharpen.jpg')
Ejemplo n.º 2
0
 def composite(self,
               composite_img,
               offset,
               compose=pgmagick.CompositeOperator.InCompositeOp):
     img = composite_img.img if type(
         composite_img) == Image else composite_img
     if isinstance(offset, (list, tuple)):
         x = int(offset[0])
         y = int(offset[1])
         offset = pgmagick.Geometry(x, y)
     elif isinstance(offset, pgmagick.Geometry):
         pass
     elif isinstance(offset, str):  # is gravity (string)
         offset = getattr(pgmagick.GravityType,
                          "%sGravity" % offset.title())
     else:  # is gravity (pgmagick.GravityType)
         pass
     if isinstance(compose, pgmagick.CompositeOperator):
         pass
     elif compose.lower() in ('copyblue', 'copygreen', 'copyopacity',
                              'copyred', 'copycyan', 'copymagenta',
                              'copyyellow', 'copyblack'):
         color = compose.lower().split('copy')[1].title()
         compose = getattr(pgmagick.CompositeOperator,
                           "Copy%sCompositeOp" % color)
     else:  # other string
         compose = getattr(pgmagick.CompositeOperator,
                           "%sCompositeOp" % compose.title())
     self.img.composite(img, offset, compose)
Ejemplo n.º 3
0
 def __init__(self, filename=None, color=None, *args, **kargs):
     self.img = None
     if sys.version_info >= (3, ) and isinstance(filename, (str)):
         self.img = pgmagick.Image(str(filename))
     elif sys.version_info < (3, ) and isinstance(filename, (unicode, str)):
         self.img = pgmagick.Image(str(filename))
     elif isinstance(filename, (list, tuple)):
         size = filename
         geometry = pgmagick.Geometry(int(size[0]), int(size[1]))
         if isinstance(color, (list, tuple)):
             r, g, b = int(color[0]), int(color[1]), int(color[2])
             color = pgmagick.Color(r, g, b)
             self.img = pgmagick.Image(geometry, color)
         elif isinstance(color, str):
             if color.find('gradient') == 0 or color.find('plasma') == 0:
                 self.img = pgmagick.Image(geometry, pgmagick.Color())
                 self.img.read(color)
             else:
                 color = pgmagick.Color(color)
                 self.img = pgmagick.Image(geometry, color)
         else:
             self.img = pgmagick.Image(geometry, pgmagick.Color())
         self.img.write(pgmagick.Blob(), 'MIFF')
     else:
         self.img = pgmagick.Image()
Ejemplo n.º 4
0
 def crop(self, *geometry):
     if len(geometry) == 4:
         width, height = geometry[0], geometry[1]
         x, y = geometry[2], geometry[3]
         g = pgmagick.Geometry(x, y, width, height)
     elif len(geometry) == 1 and isinstance(geometry[0], pgmagick.Geometry):
         g = geometry[0]
     else:
         raise Exception("not support object", geometry)
     self.img.crop(g)
Ejemplo n.º 5
0
 def scale(self, size, filter_type=None):
     if isinstance(size, float):
         scaled_height = self.img.rows() * size
         scaled_width = self.img.columns() * size
         size = "%dx%d" % (int(scaled_width), int(scaled_height))
     elif isinstance(size, (list, tuple)):
         scaled_width, scaled_height = int(size[0]), int(size[1])
         size = "%dx%d" % (int(scaled_width), int(scaled_height))
     if filter_type:
         filter_type = getattr(pgmagick.FilterTypes,
                               "%sFilter" % filter_type.title())
         pgmagick.Image.filterType(self.img, filter_type)
     geometry = pgmagick.Geometry(size)
     self.img.scale(geometry)
Ejemplo n.º 6
0
    def _resize_using_pg(self, image, width, height, mode):
        """ Resize using image mode. """

        blob = pg.Blob(image)
        blob_out = pg.Blob()
        img = pg.Image(blob)
        img.filterType(pg.FilterTypes.LanczosFilter)

        img = process_image_with_mode(img, width, height, mode)

        # Image should be repaged after a crop/resize
        img.page(pg.Geometry(0, 0, 0, 0))
        img.quality(90)  # minimise artifacts but keep size down

        img.write(blob_out, 'JPEG')
        return blob_out.data, img.size().width(), img.size().height()
Ejemplo n.º 7
0
def _resizecomp(img, width, height):
    """ Used to be called 'normal'
        This:
          First performs a box resize on the original image
          Secondly, composites the image on to a white square of the required wxh
        Mode key: 'resizecomp'
    """

    img.scale('%sx%s' % (width, height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (int(width) - img.size().width()) / 2
    hdiff = (int(height) - img.size().height()) / 2
    backdrop.composite(img, wdiff, hdiff, pg.CompositeOperator.AtopCompositeOp)
    img = backdrop

    return img
Ejemplo n.º 8
0
    def _resize_using_pg(self, image, width, height, mode):
        """ Resize using image mode. """

        blob = pg.Blob(image)
        blob_out = pg.Blob()
        img = pg.Image(blob)
        img.filterType(pg.FilterTypes.LanczosFilter)

        img = process_image_with_mode(img, width, height, mode)

        # Image should be repaged after a crop/resize
        img.page(pg.Geometry(0, 0, 0, 0))
        if settings.IMAGE_QUALITY is not None:  # May be handled by custom mode
            img.quality(settings.IMAGE_QUALITY)

        img.write(blob_out, 'JPEG')
        return blob_out.data, img.size().width(), img.size().height()
Ejemplo n.º 9
0
def _trim_resize(img, width, height):
    """ This:
          First performs a trim on the image with no color fuzz
          Secondly, performs a box resize on the original image only if the image is larger
            than the target size
          Thirdly, composites the image on to a white square of the required wxh
        Mode key: 'trimresize'
    """

    img.trim()

    w, h = img.size().width(), img.size().height()
    if w > int(width) or h > int(height):
        img.scale('%sx%s' % (width, height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (int(width) - img.size().width()) / 2
    hdiff = (int(height) - img.size().height()) / 2
    backdrop.composite(img, wdiff, hdiff, pg.CompositeOperator.AtopCompositeOp)
    img = backdrop

    return img
Ejemplo n.º 10
0
def _crop(img, width, height):
    """ This:
          First performs a box resize on the original image, but so only the smallest
            dimension is in the box. So if width was smaller, the image would be resized
            to Wx?
          Secondly, The image is cropped to the desired size, trimming the edges that are
            outside of the box
        Mode key: 'crop'
    """

    if img.size().width() < img.size().height():
        img.scale('%sx999999' % (width))
    else:
        img.scale('999999x%s' % (height))

    backdrop = pg.Image(pg.Geometry(int(width), int(height)), 'white')
    wdiff = (img.size().width() - int(width)) / 2
    hdiff = (img.size().height() - int(height)) / 2
    backdrop.composite(img, -wdiff, -hdiff, pg.CompositeOperator.CopyCompositeOp)
    img = backdrop

    return img
Ejemplo n.º 11
0
 def annotate(self, string, position=(0, 0), gravity='center', angle=0):
     position = pgmagick.Geometry(int(position[0]), int(position[1]))
     gravity = getattr(pgmagick.GravityType, "%sGravity" % gravity.title())
     self.img.annotate(string, position, gravity, angle)
Ejemplo n.º 12
0
def pgmagick_scale_from_blob(filename, width, height):
    im = pgmagick.Image(pgmagick.Blob(open(filename).read()),
                        pgmagick.Geometry(width, height))
    im.scale('%dx%d' % (width, height))
    im.quality(95)
    im.write('outpg_fromblob.jpg')
    def render(self, out_path, size=10000, scale=5, bg_color='#0b131a'):
        """
        Render a PNG.
        """

        image = pgm.Image(
            pgm.Geometry(size, size),
            pgm.Color(bg_color),
        )

        # TODO: font

        nodes = self.graph.nodes_iter(data=True)
        count = len(self.graph)

        for tid, n in progress.bar(nodes, expected_size=count):

            # Get X/Y, radius.
            x = (n['x'] * scale) + (size / 2)
            y = -(n['y'] * scale) + (size / 2)
            r = (n['size'] * scale) / 2

            # Index the coordinates.
            self.graph.node[tid]['pixel_x'] = x
            self.graph.node[tid]['pixel_y'] = y
            self.graph.node[tid]['pixel_r'] = r

            # ** Node **

            # Hex-ify color.
            color = '#%02x%02x%02x' % (n['r'], n['g'], n['b'])

            # Draw the node.
            dl = pgm.DrawableList()
            dl.append(pgm.DrawableFillColor(color))
            dl.append(pgm.DrawableStrokeColor('black'))
            dl.append(pgm.DrawableStrokeWidth(r / 15))
            dl.append(pgm.DrawableStrokeOpacity(0.9))
            dl.append(pgm.DrawableCircle(x, y, x + r, y + r))
            image.draw(dl)

            # ** Label **

            label = ', '.join([
                n['label'],
                n['author'],
            ])

            # Measure the width of the label.
            image.fontPointsize(n['size'])
            tm = pgm.TypeMetric()
            image.fontTypeMetrics(label, tm)
            tw = tm.textWidth()

            # Draw the label.
            dl = pgm.DrawableList()
            dl.append(pgm.DrawablePointSize(n['size']))
            dl.append(pgm.DrawableFillColor('white'))
            dl.append(pgm.DrawableText(x - (tw / 2), y, label))
            image.draw(dl)

        image.write(os.path.abspath(out_path))
        # TODO VERY IMPORTANT: 'fullpath_resized' needs to exist even if the original_size images is chosen!!!!!
        #                       In the very end, we need to crop the images, so we do not want to alter the
        #                       Original images!
        # Resize the picture to perform the rest of the calculations mush faster
        if options.output_res != "original_size":
            if source_dimension_x > RESOLUTIONS[options.output_res][0] or source_dimension_y > RESOLUTIONS[options.output_res][1]:
                tmp_dir = "{}resized_tmp".format(working_dir)
                # TODO: If the path exists, check for a config file to resume operations.
                #       Make a command line option to tune this behavior
                if os.path.isdir(tmp_dir):
                    pass
                    #shutil.rmtree(tmp_dir)
                else:
                    os.makedirs(tmp_dir)

                geometry = pgmagick.Geometry(resized_width, resized_height) # Specifies the desired width, height.
                geometry.aspect(False) # False = maintain aspect ratio.
                img.quality(100)    # Use the maximum quality to avoid quality loss
                img.scale(geometry) # Perform the resize.
                img_dict[image]['fullpath_resized'] = "{}/{}".format(tmp_dir, image)
                img_dict[image]['fullpath'] = img_dict[image]['fullpath_resized']
                img.write(img_dict[image]['fullpath_resized'])
        else:
            img_dict[image]['fullpath'] = img_dict[image]['fullpath_original']



    # Sort the images by capture date and store them in an OrderedDict
    img_dict = OrderedDict(sorted(img_dict.items(), key=lambda x: x[1]['exif:DateTimeDigitized']))
    #print_(img_dict)