예제 #1
0
    def genImage(self):
        """Create a PNG from the contents of this flowable.

        Required so we can put inline math in paragraphs.
        Returns the file name.
        The file is caller's responsability.

        """

        dpi = 72
        scale = 10

        try:
            import Image
            import ImageFont
            import ImageDraw
            import ImageColor
        except ImportError:
            from PIL import (
                Image,
                ImageFont,
                ImageDraw,
                ImageColor,
            )

        if not HAS_MATPLOTLIB:
            img = Image.new('L', (120, 120), ImageColor.getcolor("black", "L"))
        else:
            width, height, descent, glyphs,\
            rects, used_characters = self.parser.parse(
                enclose(self.s), dpi)
            img = Image.new('L', (int(width*scale), int(height*scale)),
                ImageColor.getcolor("white", "L"))
            draw = ImageDraw.Draw(img)
            for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                font = ImageFont.truetype(fontname, int(fontsize*scale))
                tw, th = draw.textsize(unichr(num), font=font)
                # No, I don't understand why that 4 is there.
                # As we used to say in the pure math
                # department, that was a numerical solution.
                draw.text((ox*scale, (height - oy - fontsize + 4)*scale),
                           unichr(num), font=font)
            for ox, oy, w, h in rects:
                x1 = ox*scale
                x2 = x1 + w*scale
                y1 = (height - oy)*scale
                y2 = y1 + h*scale
                draw.rectangle([x1, y1, x2, y2],
                               fill=ImageColor.getcolor("black", "L"))

        fh, fn = tempfile.mkstemp(suffix=".png")
        os.close(fh)
        img.save(fn)
        return fn
예제 #2
0
def brightness(image, amount=50):
    """Adjust brightness from black to white
    - amount: -1(black) 0 (unchanged) 1(white)
    - repeat: how many times it should be repeated"""
    if amount == 0:
        return image

    image = imtools.convert_safe_mode(image)

    if amount < 0:
        #fade to black
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size, 0),
                -amount / 100.0)
    else:
        #fade to white
        im = imtools.blend(
                image,
                Image.new(image.mode, image.size,
                    ImageColor.getcolor('white', image.mode)),
                amount / 100.0)
    #fix image transparency mask
    if imtools.has_alpha(image):
        im.putalpha(imtools.get_alpha(image))
    return im
예제 #3
0
    def run(self):
        self._d24.debug('Running!')
        orig = Image.open("unpacked/%s.jpg" % self._name)
        draw = ImageDraw.Draw(orig)
        size = orig.size
        res = Image.open("unpacked/%s-act.jpg" % self._name)
        while not self.stopit:
            for r, row in enumerate(self._piece):
                for c, cell in enumerate(row):
                    if not cell[2]:
                        continue

                    im = Image.open("unpacked/%s/%s-%d-%d.jpg" %
                                    (self._name, self._name, r + 1, c + 1))
                    cwidth, cheight = im.size
                    im = im.rotate(rotator[cell[3]])
                    res.paste(im, (cell[1] * cwidth, cell[0] * cheight,
                                   (cell[1] + 1) * cwidth,
                                   (cell[0] + 1) * cheight))
                    draw.rectangle(((c * cwidth, r * cheight),
                                    ((c + 1) * cwidth, (r + 1) * cheight)),
                                   ImageColor.getcolor('black', 'RGB'))

            res.save("unpacked/%s-act.jpg" % self._name)
            orig.save("unpacked/%s.jpg" % self._name)
            self._d24.debug('Drawed')
            time.sleep(2)

        self._d24.debug('Closed!')
예제 #4
0
파일: ImageDraw.py 프로젝트: nh/imgc
 def setink(self, ink):
     # compatibility
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
예제 #5
0
    def pt2color(self, map, pt, max):
        v = self.mapget(map, pt)
        c = 100 - min(v, max) * 100 / max
        h = 3.6 * c

        return ImageColor.getcolor(
            'hsl(' + str(int(h)) + ',' + str(c) + '%,' + str(c) + '%)', 'RGB')
예제 #6
0
    def genImage(self):
        """Create a PNG from the contents of this flowable.

        Required so we can put inline math in paragraphs.
        Returns the file name.
        The file is caller's responsability.

        """

        dpi = 72
        scale = 10

        import Image
        import ImageFont
        import ImageDraw
        import ImageColor

        if not HAS_MATPLOTLIB:
            img = Image.new('L', (120, 120), ImageColor.getcolor("black", "L"))
        else:
            width, height, descent, glyphs,\
            rects, used_characters = self.parser.parse(
                '$%s$' % self.s, dpi)
            img = Image.new('L', (int(width * scale), int(height * scale)),
                            ImageColor.getcolor("white", "L"))
            draw = ImageDraw.Draw(img)
            for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
                font = ImageFont.truetype(fontname, int(fontsize * scale))
                tw, th = draw.textsize(unichr(num), font=font)
                # No, I don't understand why that 4 is there.
                # As we used to say in the pure math
                # department, that was a numerical solution.
                draw.text((ox * scale, (height - oy - fontsize + 4) * scale),
                          unichr(num),
                          font=font)
            for ox, oy, w, h in rects:
                x1 = ox * scale
                x2 = x1 + w * scale
                y1 = (height - oy) * scale
                y2 = y1 + h * scale
                draw.rectangle([x1, y1, x2, y2],
                               fill=ImageColor.getcolor("black", "L"))

        fh, fn = tempfile.mkstemp(suffix=".png")
        os.close(fh)
        img.save(fn)
        return fn
예제 #7
0
	def build_tree():
		tree = Quad(Rect(0, 0, size, size))
		level = Level(Rect(0, 0, size, size))
		level.color = ImageColor.getcolor('grey', mode)
		tree.charge(level)

		room = Room(Rect(4, 4, 16, 16), level, name='room')
		room.color = ImageColor.getcolor('orange', mode)
		tree.charge(room)

		table = Furniture(Rect(0, 0, 4, 3), room, name='table')
		table.color = ImageColor.getcolor('brown', mode)

		lamp = Furniture(Rect(1, 1, 1, 1), table, name='lamp')
		lamp.color = ImageColor.getcolor('yellow', mode)

		tree.charge(table)

		bed = Bed(Rect(4, 0, 4, 8), room, color=ImageColor.getrgb('white'),
				 decor_color=ImageColor.getrgb('darkcyan'))
		tree.charge(bed)

		bed2 = Bed(Rect(9, 0, 4, 8), room, color=ImageColor.getrgb('white'),
				 decor_color=ImageColor.getrgb('crimson'))
		tree.charge(bed2)

		bed2.tear_down()

		#bed = Furniture(Rect(4, 0, 4, 8), room, name='bed')
		#bed.color = ImageColor.getcolor('green', mode)
		#tree.charge(bed)

		#pillow = Furniture(Rect(1, 1, 2, 1), bed, name='pillow')
		#pillow.color = ImageColor.getcolor('white', mode)
		#tree.charge(pillow)

		#sheet = Furniture(Rect(0, 3, 4, 5), bed, name='sheet')
		#sheet.color = ImageColor.getcolor('white', mode)
		#tree.charge(sheet)

		lump = Block(Rect(32, 32, 8, 8), room, name='lump', abs=True)
		lump.color = ImageColor.getcolor('black', mode)
		tree.charge(lump)

		return tree
예제 #8
0
 def setink(self, ink):
     # compatibility
     if warnings:
         warnings.warn("'setink' is deprecated; use keyword arguments instead", DeprecationWarning, stacklevel=2)
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
예제 #9
0
 def _getink(self, ink, fill=None):
     if ink is None and fill is None:
         if self.fill:
             fill = self.ink
         else:
             ink = self.ink
     else:
         if ink is not None:
             if Image.isStringType(ink):
                 ink = ImageColor.getcolor(ink, self.mode)
             if self.palette and not Image.isNumberType(ink):
                 ink = self.palette.getcolor(ink)
             ink = self.draw.draw_ink(ink, self.mode)
         if fill is not None:
             if Image.isStringType(fill):
                 fill = ImageColor.getcolor(fill, self.mode)
             if self.palette and not Image.isNumberType(fill):
                 fill = self.palette.getcolor(fill)
             fill = self.draw.draw_ink(fill, self.mode)
     return ink, fill
예제 #10
0
 def setink(self, ink):
     # compatibility
     if warnings:
         warnings.warn(
             "'setink' is deprecated; use keyword arguments instead",
             DeprecationWarning)
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
예제 #11
0
파일: ImageDraw.py 프로젝트: 12mvp/pil1.1.6
 def _getink(self, ink, fill=None):
     if ink is None and fill is None:
         if self.fill:
             fill = self.ink
         else:
             ink = self.ink
     else:
         if ink is not None:
             if Image.isStringType(ink):
                 ink = ImageColor.getcolor(ink, self.mode)
             if self.palette and not Image.isNumberType(ink):
                 ink = self.palette.getcolor(ink)
             ink = self.draw.draw_ink(ink, self.mode)
         if fill is not None:
             if Image.isStringType(fill):
                 fill = ImageColor.getcolor(fill, self.mode)
             if self.palette and not Image.isNumberType(fill):
                 fill = self.palette.getcolor(fill)
             fill = self.draw.draw_ink(fill, self.mode)
     return ink, fill
예제 #12
0
def get_ink_with_alpha(self, fill=None, alpha=None):
    ink = self.ink if (fill == None) else fill
    if ink == None:
        return ink
    if Image.isStringType(ink):
        ink = ImageColor.getcolor(ink, self.mode)
    if self.palette and not Image.isNumberType(ink):
        ink = self.palette.getcolor(ink)
    if alpha != None:  #and self.mode == "RGBA"
        ink = ink[:3] + (alpha, )
    #print ink
    return self.draw.draw_ink(ink, self.mode)
예제 #13
0
파일: texteffect.py 프로젝트: pyzzz/mygtk
def get_ink_with_alpha(self, fill=None, alpha=None):
	ink = self.ink if (fill == None) else fill
	if ink == None:
		return ink
	if Image.isStringType(ink):
		ink = ImageColor.getcolor(ink, self.mode)
	if self.palette and not Image.isNumberType(ink):
		ink = self.palette.getcolor(ink)
	if alpha != None: #and self.mode == "RGBA"
		ink = ink[:3]+(alpha,)
	#print ink
	return self.draw.draw_ink(ink, self.mode)
예제 #14
0
 def __init__(self, mode='RGBA', size=(320, 240),
              background_color=(255, 255, 255)):
     Image.Image.__init__(self)
     if background_color == None:
         im = Image.core.new(mode, size)
     else:
         color_type = type(background_color).__name__
         if color_type == 'str' or color_type == 'unicode':
             background_color = ImageColor.getcolor(background_color, mode)
         im = Image.core.fill(mode, size, background_color)
     self.im = im
     self.mode = im.mode
     self.size = im.size
     if im.mode == 'P':
         self.palette = ImagePalette.ImagePalette()
예제 #15
0
def ppng(f, names, matrix, nodes, classifier, coloration, signature, outFileName, opt):
  import Image, ImageColor
  zoom = 2
  steps = classifier(matrix)
  colors = coloration(0, 1., steps, get_color_html)
  l = len(nodes)
  h = l * zoom

  image = Image.new("RGBA", (h, h))
  for i, n in enumerate(nodes):
    for j in xrange(l):
      cls, c = get_color(matrix[(i, j)], steps, colors)
      for k1 in xrange(zoom) :
        for k2 in xrange(zoom) :
          rgba = ImageColor.getcolor(c, "RGBA")
          image.putpixel((i*zoom+k1, j*zoom+k2), rgba) 
  image.save(f,"png")
예제 #16
0
	def test():
		scaled = size*scale

		im = Image.new(
			mode, (scaled, scaled),
			color=ImageColor.getcolor('rgb(124, 124, 124)', mode)
		)
		canvas = ImageDraw.Draw(im)

		tree = build_tree()
		draw_tree(tree, canvas)

		#box = [Point(size/6, size/6) * scale, (Point(size-size/6, size-size/6) * scale)-1]
		#canvas.rectangle(box, fill=colors[random.randint(0, 1)])
		im = im.resize((size*10, size*10))
		name = 'level.png'
		logging.info("Saving to %s" % name)
		im.save(name)
예제 #17
0
def ppng(f, names, matrix, nodes, classifier, coloration, signature,
         outFileName, opt):
    import Image, ImageColor
    zoom = 2
    steps = classifier(matrix)
    colors = coloration(0, 1., steps, get_color_html)
    l = len(nodes)
    h = l * zoom

    image = Image.new("RGBA", (h, h))
    for i, n in enumerate(nodes):
        for j in xrange(l):
            cls, c = get_color(matrix[(i, j)], steps, colors)
            for k1 in xrange(zoom):
                for k2 in xrange(zoom):
                    rgba = ImageColor.getcolor(c, "RGBA")
                    image.putpixel((i * zoom + k1, j * zoom + k2), rgba)
    image.save(f, "png")
예제 #18
0
파일: utils.py 프로젝트: fserb/gchart
def make_brasil_map(data, finalsize=None):
  brasil_png = os.path.join(os.path.split(__file__)[0], 'brasil.png')
  raw = Image.open(brasil_png).copy()
  mapa = Image.new('RGBA', raw.size, 'white')
  mapa.paste(raw, (0, 0))

  for k in data:
    if k in places:
      if type(data[k]) == str:
        color = ImageColor.getcolor('#'+data[k], 'RGBA')
      else:
        color = data[k]
      ImageDraw.floodfill(mapa, places[k], color)

  if finalsize:
    mapa = mapa.resize(finalsize)

  dump = StringIO.StringIO()
  mapa.save(dump, 'PNG')
  return dump.getvalue()
예제 #19
0
def brightness(image, amount=50):
    """Adjust brightness from black to white
    - amount: -1(black) 0 (unchanged) 1(white)
    - repeat: how many times it should be repeated"""
    if amount == 0:
        return image

    image = imtools.convert_safe_mode(image)

    if amount < 0:
        #fade to black
        im = imtools.blend(image, Image.new(image.mode, image.size, 0),
                           -amount / 100.0)
    else:
        #fade to white
        im = imtools.blend(
            image,
            Image.new(image.mode, image.size,
                      ImageColor.getcolor('white', image.mode)),
            amount / 100.0)
    #fix image transparency mask
    if imtools.has_alpha(image):
        im.putalpha(imtools.get_alpha(image))
    return im
예제 #20
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
예제 #21
0
 def pt2color(self, map, pt, max):
     v = self.mapget(map, pt)
     c = 100 - min(v,max) * 100 / max
     h = 3.6 * c
     
     return ImageColor.getcolor('hsl('+str(int(h))+','+str(c)+'%,'+str(c)+'%)', 'RGB')
예제 #22
0
def _color(color, mode):
    if Image.isStringType(color):
        import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color
예제 #23
0
파일: ImageOps.py 프로젝트: 0xD34DC0DE/PIL
def _color(color, mode):
    if Image.isStringType(color):
        import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color
예제 #24
0
파일: rek2.py 프로젝트: Neverous/team
	def run(self):
		self._d24.debug('Running!')
		orig = Image.open("unpacked/%s.jpg" % self._name)
		draw = ImageDraw.Draw(orig)
		size = orig.size
		res = Image.open("unpacked/%s-act.jpg" % self._name)
		while not self.stopit:
			for r, row in enumerate(self._piece):
				for c, cell in enumerate(row):
					if not cell[2]:
						continue

					im = Image.open("unpacked/%s/%s-%d-%d.jpg" % (self._name, self._name, r + 1, c + 1))
					cwidth, cheight = im.size
					im = im.rotate(rotator[cell[3]])
					res.paste(im, (cell[1] * cwidth, cell[0] * cheight, (cell[1] + 1) * cwidth, (cell[0] + 1) * cheight))
					draw.rectangle(((c * cwidth, r * cheight), ((c + 1) * cwidth, (r + 1) * cheight)), ImageColor.getcolor('black', 'RGB'))

			res.save("unpacked/%s-act.jpg" % self._name)
			orig.save("unpacked/%s.jpg" % self._name)
			self._d24.debug('Drawed')
			time.sleep(2)

		self._d24.debug('Closed!')
                  help="Color for reverse alignments (default: %default)")
(opts, args) = parser.parse_args()
if len(args) != 2: parser.error("2 arguments needed")

if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
else:              font = ImageFont.load_default()

# Make these options too?
text_color = "black"
background_color = "white"
pix_tween_seqs = 2  # number of border pixels between sequences
border_shade = 239, 239, 239  # the shade of grey to use for border pixels
label_space = 5     # minimum number of pixels between axis labels

image_mode = 'RGB'
forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
overlap_color = tuple([(i+j)//2 for i, j in zip(forward_color, reverse_color)])

def isGapless(alignmentColumn):
    return "-" not in alignmentColumn

def matchAndInsertLengths(alignmentColumns):
    for k, v in itertools.groupby(alignmentColumns, isGapless):
        if k:
            matchLength = sum(1 for i in v)
            yield str(matchLength)
        else:
            blockRows = itertools.izip(*v)
            insertLengths = (len(i) - i.count("-") for i in blockRows)
            yield ":".join(map(str, insertLengths))
예제 #26
0
파일: grid.py 프로젝트: Reimilia/Camellia
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