Example #1
0
    def make_check_code_image(self, image=''):

        color = ImageColor.getrgb('white')
        #im = Image.open(image)
        im = Image.new('RGB',(60,20), color) 
        draw = ImageDraw.Draw(im) 
        
        mp = md5.new() 
        mp_src = mp.update(str(datetime.datetime.now())) 
        mp_src = mp.hexdigest()

        rand_str = mp_src[0:4] 
        #print rand_str
        color = ImageColor.getrgb('LightGray')
        for i in range(200):
            x = random.randrange(1,60)
            y = random.randrange(1,20)
            draw.point((x, y), fill=color)
        
        draw.text((5, 1), rand_str[0], fill = self.get_color(), font = self.get_font())
        draw.text((15, 1), rand_str[1], fill = self.get_color(), font = self.get_font())
        draw.text((30, 1), rand_str[2], fill = self.get_color(), font = self.get_font())
        draw.text((45, 1), rand_str[3], fill = self.get_color(), font = self.get_font())
        
        draw.line((0, 10, 60, 15), fill = self.get_color())
        
        del draw 
        session['checkcode'] = rand_str 
        buf = StringIO.StringIO()   
        im.save(buf, 'gif')
        buf.closed
        if image: 
            im.save(image) 
        return buf.getvalue()
Example #2
0
def colorize(data, colormap):
    #data = np.zeros((256, 256), dtype=np.float32)
    #data.data = raw.data
    out = np.zeros((256, 256, 4), dtype=np.uint8)
    tmp = np.zeros((256, 256), dtype=np.uint32)
    tmp.data = out.data
    
    c = np.zeros(4, dtype=np.uint8)
    d = np.zeros(1, dtype=np.uint32)
    d.data = c.data
    
    if colormap['missing']: c[0:3] = ImageColor.getrgb(colormap['missing'])
    else: c[0:3] = 0
    c[3] = 255
    tmp[...] = d
    
    n = 0
    for b in colormap['bounds']:
        step = 1.0*(b['end'] - b['start'])/b['steps']
        for i in range(b['steps']):
            low = b['start'] + i*step
            high = low + step
            mask = np.logical_and(data > low, data < high)
            c[0:3] = ImageColor.getrgb(colormap['colors'][n + i])
            tmp[mask] = d
        n += b['steps']
    
    return out
Example #3
0
    def draw_baselines(self, img_in):
        img_out = img_in.copy()
        draw = ImageDraw.Draw(img_out)
    
        prev_floor = 0
        w, h = img_out.size
    
        gap_color = ImageColor.getrgb('#ccccFF')
    
        lines = scrape.calc_lines(scrape.font_metrics(), 7)

        for i, (ceiling, base, floor) in enumerate(lines):

            # draw the baseline
            color = ImageColor.getrgb("#ffdddd")
            if not base:
                base = floor -2
                color = ImageColor.getrgb("red")
    
            draw.line([(0, base), (w, base)], fill=color)
            
            # shade gap between the lines
            draw.rectangle((0, prev_floor, w, ceiling), fill=gap_color)
            prev_floor = floor +1
                
        # shade final gap:
        draw.rectangle((0, prev_floor, w, h), fill=gap_color)
    
        # now draw the text back over the baselines:
        img_out = ImageChops.darker(img_in, img_out)

        # uncomment to zoom in for debugging
        # img_out = img_out.resize((w *2 , h* 2))

        return img_out
Example #4
0
def main():
    global back, couleurs, grids, thumbs

    #----- Main code ------------------------
    console.clear()

    grids = [
        '1', '12', '1/2', '123', '11/23', '12/33', '1/2/3', '12/32', '12/13',
        '1234', '111/234', '12/34', '123/444', '11/22/34', '12/33/44',
        '11/23/44', '1/2/3/4', '12/13/14', '12/32/42', '11/23/43', '123/143',
        '123/425', '1234/5678/9abc/defg', '12345/67890/abcde/fghij/klmno'
    ]  #, '5', '1/4', '4/1', '2/3', f'3/2', '1/1/3', '1/3/1', '2/1/2', '2/2/1', '1/2/2', '3/1/1','1/1/1/2', '1/1/2/1', '1/2/1/1', '2/1/1/1', '1/1/1/1/1']

    couleurs = [
        'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige',
        'bisque', 'blanchedalmond', 'burlywood', 'cadetblue', 'chartreuse',
        'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan',
        'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue',
        'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro',
        'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow',
        'grey', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki',
        'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
        'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray',
        'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',
        'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue',
        'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon',
        'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple',
        'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
        'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
        'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 'olive',
        'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod',
        'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip',
        'peachpuff', 'peru', 'pink', 'plum', 'powderblue', 'purple', 'red',
        'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown',
        'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
        'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan',
        'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white',
        'whitesmoke', 'yellow', 'yellowgreen', 'black', 'blue', 'blueviolet',
        'brown', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray',
        'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta', 'darkolivegreen',
        'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen',
        'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise',
        'darkviolet'
    ]
    # Sort colors on HSL H=Hue(teinte) S=Saturation L=Lightness(luminosité)
    couleurs = sorted(couleurs,
                      key=lambda x: colorsys.rgb_to_hsv(
                          ImageColor.getrgb(x)[0],
                          ImageColor.getrgb(x)[1],
                          ImageColor.getrgb(x)[2]))

    w, h = ui.get_screen_size()
    disp = 'full_screen'
    back = MyView(w, h)
    back.background_color = 'white'
    back.present(disp, hide_title_bar=True)

    thumbs = {}
Example #5
0
	def init(self, color=ImageColor.getrgb('white'),
			 decor_color=ImageColor.getrgb('blue')):
		self.color = color

		self.pillow = Decor(Rect(1, 1, 2, 1), self, 'pillow')
		self.pillow.color = decor_color

		self.sheet = Decor(Rect(0, 3, 4, 5), self, 'sheet')
		self.sheet.color = decor_color
Example #6
0
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8):

    import PIL
    import Image, ImageDraw, ImageColor, ImageFont

    WIDTH = 100
    HEIGHT = 18

    def centerTextInBox(font, text, size):
        center = [0, 0]
        center[0] = size[0] / 2.0 - font.getsize(text)[0] / 2.0
        center[1] = size[1] / 2.0 - font.getsize(text)[1] / 2.0 + 1
        return center

    im = Image.new("RGBA", (WIDTH, HEIGHT))

    outline = ImageColor.getrgb("#000000")
    background = ImageColor.getrgb("#4697ff")
    bar = ImageColor.getrgb("#14ff00")
    barWarn = ImageColor.getrgb("#ff0f00")
    textColour = ImageColor.getrgb("#000000")

    try:
        percentage = float(value) / range
    except:
        percentage = 0.0

    if percentage > warnThreshold:
        barColour = barWarn
    else:
        barColour = bar
    barWidth = percentage * im.size[0]
    barWidth = min(barWidth, im.size[0])

    draw = ImageDraw.Draw(im)
    draw.rectangle([0, 0, im.size[0] - 1, im.size[1] - 1],
                   outline=outline,
                   fill=background)
    draw.rectangle([0, 0, barWidth - 1, im.size[1] - 1],
                   outline=outline,
                   fill=barColour)

    font = ImageFont.load_default()
    try:
        font = ImageFont.truetype("/var/tmp/Nimbus Sans L,", 16)
    except:
        debugOutput("Cannot load Nimbus font")
        font = ImageFont.load_default()
    if text:
        draw.text(centerTextInBox(font, text, im.size),
                  text,
                  font=font,
                  fill=textColour)

    if not drool.settings.options.testRun:
        im.save(file)
def general_filling_rec(fillcolor, bordercolor, maxX, maxY, draw, pic, x, y):
    sys.setrecursionlimit(100000)
    fc = ImageColor.getrgb(fillcolor)
    bc = ImageColor.getrgb(bordercolor)

    def GFill(x, y):
        if 0 < x < maxX and 0 < y < maxY:
            color = pic.getpixel((x, y))
            if color != bc and color != fc:
                draw.point([x, y], fc)
                GFill(x + 1, y)
                GFill(x, y + 1)
                GFill(x - 1, y)
                GFill(x, y - 1)
Example #8
0
def create_cluster_colors_rgb(n, normalize=True):
    # create n distinct colors in rgb format

    colors = []
    for i in range(n):
        h = int( float(i) / float(n) *  360.0 )
        s = 50
        l = 50
        if normalize:
            colors.append(np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l))) / 255.0 )
        else:
            colors.append(np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l))))

    return colors
Example #9
0
def writeProgressImage(value, range, file, text=None, warnThreshold=0.8) :

  import PIL
  import Image, ImageDraw, ImageColor, ImageFont

  WIDTH = 100
  HEIGHT = 18

  def centerTextInBox(font, text, size) :
    center = [0,0]
    center[0] = size[0]/2.0 - font.getsize(text)[0]/2.0
    center[1] = size[1]/2.0 - font.getsize(text)[1]/2.0 + 1
    return center

  im = Image.new("RGBA",(WIDTH, HEIGHT))

  outline = ImageColor.getrgb("#000000")
  background = ImageColor.getrgb("#4697ff")
  bar = ImageColor.getrgb("#14ff00")
  barWarn = ImageColor.getrgb("#ff0f00")
  textColour = ImageColor.getrgb("#000000")

  try :
    percentage = float(value)/range
  except :
    percentage = 0.0

  if percentage > warnThreshold :
    barColour = barWarn
  else :
    barColour = bar
  barWidth = percentage * im.size[0]
  barWidth = min(barWidth, im.size[0])

  draw = ImageDraw.Draw(im)
  draw.rectangle([0,0, im.size[0]-1, im.size[1]-1], outline=outline, fill=background)
  draw.rectangle([0,0, barWidth-1, im.size[1]-1], outline=outline, fill=barColour)

  font = ImageFont.load_default()
  try :
    font = ImageFont.truetype("/var/tmp/Nimbus Sans L,",16)
  except :
    debugOutput("Cannot load Nimbus font")
    font = ImageFont.load_default()
  if text :
    draw.text(centerTextInBox(font, text, im.size), text, font=font, fill=textColour)

  if not drool.settings.options.testRun : 
    im.save(file)
Example #10
0
def drawSkin(imagePath, size, outlineColour, bgColour) :
  import PIL
  import Image, ImageDraw, ImageColor, ImageFont
  
  borderWidth = 2
  
  im = Image.new("RGBA",(size[0], size[1]))

  outline = ImageColor.getrgb(outlineColour)
  background = ImageColor.getrgb(bgColour)

  draw = ImageDraw.Draw(im)
  draw.rectangle([0,0, im.size[0]-1, im.size[1]-1], outline=outline, fill=background)

  im.save(imagePath)
Example #11
0
    def display_distance_LUT(self, dlut, sname):
        display_im = self.im.copy()
        draw = ImageDraw.Draw(display_im)
        max_d = 0

        for gx in range(self.grid_width - 1):
            for gy in range(self.grid_height - 1):
                (x, y) = self.grid_to_map((gx, gy))
                if (gx, gy) in self.occupied:
                    continue
                min_d = 40.0
                for ga in range(self.num_angles - 1):
                    d = dlut.distance(x, y,
                                      self.discrete_angle_to_map_angle(ga))
                    if d < min_d:
                        min_d = d
                if min_d > max_d:
                    max_d = min_d
                rvalue = int(255 - (min_d * 255 / 5.0))
                if rvalue < 0:
                    rvalue = 0
                self.draw_grid_rectangle(
                    gx, gy, draw,
                    ImageColor.getrgb('rgb(' + str(rvalue) + ',0,0)'))

        #Save the image
        display_im.save(sname)
        del draw
        del display_im
Example #12
0
def color_bg(request, color, opacity=100):
    """
    Generates a 10x10 square image in the color requested.
    Useful for generating background colors based on user-provided 
    color settings.
    """
    import Image, ImageDraw, ImageColor

    alpha = int((int(opacity) / 100.0) * 255)

    if len(color) != 3 and len(color) != 6:
        raise Http404
    color = "#%s" % color
    color = ImageColor.getrgb(color) + (alpha,)

    size = (10, 10)

    etag = md5_constructor("%s%s" % (color, size)).hexdigest()
    if request.META.get("HTTP_IF_NONE_MATCH") == etag:
        return HttpResponseNotModified()

    img = Image.new("RGBA", size=size, color=color)

    response = HttpResponse(mimetype="image/png")
    img.save(response, "PNG")
    response["Etag"] = etag
    return response
Example #13
0
def ent2img(visited_tab, m):
    global red

    target_px_w = 640
    target_px_h = 480
    target_px = target_px_w * target_px_h
    target_dim = (target_px_w, target_px_h)
    m.write()

    # only care about coverage for regions that are exec
    if not m.is_exec():
        return None

    # ignore empty regions, if any
    if m.end - m.begin == 0:
        return None

    pixels_per_byte = float(target_px) / float(m.end - m.begin)
    if pixels_per_byte == 0:
        print "0 pixels per byte. Whoops"
        return None

    im = Image.new("RGB", target_dim, ImageColor.getrgb("black"))
    for (k, num_bytes) in visited_tab.items():
        if k < m.begin or k + num_bytes > m.end:
            continue
        offset = int(pixels_per_byte * (k - m.begin))
        for i in range(0, int(num_bytes * pixels_per_byte)):
            x = (offset + i) % target_px_w
            y = (offset + i) / target_px_w
            im.putpixel((x, y), red)
    return im
def crop(image_file, bgcolor=ImageColor.getrgb("white")):
  image = Image.open(image_file,'r')
  mask = Image.new("RGB", image.size, bgcolor)
  diff = ImageChops.difference(image, mask)
  bbox = diff.getbbox()
  new_image = image.crop(bbox)
  new_image.save(image_file,"png")
Example #15
0
    def display_distance_LUT(self, dlut, sname):
        display_im = self.im.copy()
        draw = ImageDraw.Draw(display_im)

        print 'Grid w x h =', self.grid_width, self.grid_height
        max_d = 0

        for gx in range(self.grid_width-1):
            for gy in range(self.grid_height-1):
                (x,y) = self.grid_to_map((gx,gy))
                if (gx,gy) in self.occupied:
                    continue
                min_d = 40.0
                for ga in range(self.num_angles-1):
                    #print 
                    d = dlut.distance(x,y,self.discrete_angle_to_map_angle(ga))
                    #d2 = self.distance_to_obstacle((gx,gy),self.discrete_angle_to_map_angle(ga))
                    #print 'Checking <', gx, gy, ga, '> d = ', d, 'd2=',d2
                    if d < min_d:
                        min_d = d
                #print (x,y), '->', min_d
                if min_d > max_d:
                    max_d = min_d
                rvalue = int(255 - (min_d*255/5.0))
                if rvalue < 0:
                    rvalue = 0
                self.draw_grid_rectangle(gx,gy,draw,ImageColor.getrgb('rgb(' + str(rvalue) + ',0,0)'))
        print 'MAX D= ', max_d
                   
        #Save the image
        display_im.save(sname)
        del draw
        del display_im                   
Example #16
0
def assignMatPlotlibHueColorToLs(name_ls, debug=0):
    """
	2008-10-07
		assign continuous HSL color spectrum to a list (in order).
		
	"""
    if debug:
        sys.stderr.write("Assigning matplotlib hue color to a list ...")
    import ImageColor
    no_of_names = len(name_ls)
    value_step = 1. / (no_of_names - 1
                       )  #-1 to cover both minimum and maximum in the spectrum
    name2fc = {}
    for i in range(no_of_names):
        name = name_ls[i]
        value = i * value_step
        hue_value = max(min(int(round((1 - value) * 255)), 255),
                        0)  #max(min()) makes sure it's 0-255
        fc = ImageColor.getrgb(
            'hsl(%s' % hue_value + ',100%,50%)'
        )  #"hsl(hue, saturation%, lightness%)" where hue is the colour given as an
        # angle between 0 and 360 (red=0, green=120, blue=240),
        #saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%).
        fc = [color_value / 255.
              for color_value in fc]  #matplotlib accepts rgb in [0-1] range
        name2fc[name] = fc
    if debug:
        sys.stderr.write("Done.\n")
    return name2fc
Example #17
0
    def double_ended(low, zero, high, *args, **kwargs):
        '''double_ended(low, zero, high) -> ColorMap

        low, zero, high should be scalar. 

        Returns a ColorMap that is grey at zero and increases in saturation
        toward low and high.'''

        lowcolor = ImageColor.getrgb("hsl(180,100%,50%)")
        highcolor = ImageColor.getrgb("hsl(0,100%,50%)")
        zerocolor = ImageColor.getrgb("hsl(0,100%,0%)")

        points = np.asarray([ (low,) + lowcolor,
            (zero,) + zerocolor,
            (high,) + highcolor ])

        return ColorMap(points)
Example #18
0
def create_cluster_colors_rgb(n, normalize=True):
    # create n distinct colors in rgb format

    colors = []
    for i in range(n):
        h = int(float(i) / float(n) * 360.0)
        s = 50
        l = 50
        if normalize:
            colors.append(
                np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l))) /
                255.0)
        else:
            colors.append(
                np.array(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l))))

    return colors
 def __init__(self, fontname, textcol_bright, textcol_dark, textsize=40, noiselines=False, bgpicture=None, squiggly=False):
     self.font=ImageFont.truetype(fontname, textsize)
     self.lettersize=self.font.getsize('x')
     if type(textcol_bright)!=tuple:
         textcol_bright=ImageColor.getrgb(textcol_bright)
     if type(textcol_dark)!=tuple:
         textcol_dark=ImageColor.getrgb(textcol_dark)
     self.textcol_bright=textcol_bright
     self.textcol_dark=textcol_dark
     ar,ag,ab=self.textcol_bright
     self.textcol_avg=(ar+self.textcol_dark[0])/2, (ag+self.textcol_dark[1])/2, (ab+self.textcol_dark[2])/2
     self.noiselines=noiselines
     self.squiggly=squiggly
     if bgpicture:
         self.bgpicture=Image.open(bgpicture)
     else:
         self.bgpicture=None
Example #20
0
def drawSkin(imagePath, size, outlineColour, bgColour):
    import PIL
    import Image, ImageDraw, ImageColor, ImageFont

    borderWidth = 2

    im = Image.new("RGBA", (size[0], size[1]))

    outline = ImageColor.getrgb(outlineColour)
    background = ImageColor.getrgb(bgColour)

    draw = ImageDraw.Draw(im)
    draw.rectangle([0, 0, im.size[0] - 1, im.size[1] - 1],
                   outline=outline,
                   fill=background)

    im.save(imagePath)
Example #21
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
Example #22
0
	def return_rgb_color_given_score(self, score, value2color_func):
		"""
		2008-11-15
		"""
		hue_value_in_hsl_format = value2color_func(score)
		fc = ImageColor.getrgb(hue_value_in_hsl_format)	#"hsl(hue, saturation%, lightness%)" where hue is the colour given as an
		# angle between 0 and 360 (red=0, green=120, blue=240),
		#saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%).
		fc = [color_value/255. for color_value in fc]
		return fc
Example #23
0
def create_cluster_colors(n):
    # create n distinct colors in rgb format

    colors = []
    for i in range(n):
        h = int(float(i) / float(n) * 360.0)
        s = 50
        l = 50
        colors.append(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h, s, l)))

    return colors
Example #24
0
def create_cluster_colors(n):
    # create n distinct colors in rgb format

    colors = []
    for i in range(n):
        h = int( float(i) / float(n) *  360.0 )
        s = 50
        l = 50
        colors.append(ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (h,s,l)) )

    return colors
Example #25
0
 def __init__(self, colormap, background=None, background_image=None):
     '''Each argument to the constructor should be a 4-tuple of (hue,
     saturaton, value, alpha), one to use for minimum data values and
     one for maximum.  Each should be in [0,1], however because hue is
     circular, you may specify hue in any range and it will be shifted
     into [0,1] as needed.  This is so you can wrap around the color
     wheel in either direction.'''
     self.colormap = colormap
     self.background_image = background_image
     self.background = None
     if background and not background_image:
         self.background = ImageColor.getrgb(background)
Example #26
0
    def return_rgb_color_given_score(self, score, value2color_func):
        """
		2008-11-15
		"""
        hue_value_in_hsl_format = value2color_func(score)
        fc = ImageColor.getrgb(
            hue_value_in_hsl_format
        )  #"hsl(hue, saturation%, lightness%)" where hue is the colour given as an
        # angle between 0 and 360 (red=0, green=120, blue=240),
        #saturation is a value between 0% and 100% (gray=0%, full color=100%), and lightness is a value between 0% and 100% (black=0%, normal=50%, white=100%).
        fc = [color_value / 255. for color_value in fc]
        return fc
Example #27
0
 def __init__(self, colormap, background=None, background_image=None):
     '''Each argument to the constructor should be a 4-tuple of (hue,
     saturaton, value, alpha), one to use for minimum data values and
     one for maximum.  Each should be in [0,1], however because hue is
     circular, you may specify hue in any range and it will be shifted
     into [0,1] as needed.  This is so you can wrap around the color
     wheel in either direction.'''
     self.colormap = colormap
     self.background_image = background_image
     self.background = None
     if background and not background_image:
         self.background = ImageColor.getrgb(background)
Example #28
0
def build_and_print_matrices_deg_colored(v,strat):
    """old PIL solution using a different color for each degree"""
    if len(v)==0:
        return
    
    treated=BooleSet()
    v=list(v)
    rows=0
    polys_in_mat=[]

    while(len(v)>0):
        rows=rows+1
        p=v[0]
        v=v[1:]
        for m in list(p.terms()):
            m=Monomial(m)
            if not m in BooleSet(treated):
                i=strat.select(m)
                if i>=0:
                    p2=strat[i]
                    p2=p2*(m//p2.lead())
                    v.append(p2)
        polys_in_mat.append(p)
        treated=treated.union(p.set())
    m2i=dict([(v,k) for (k,v) in enumerate(BooleSet(treated))])
    max_deg=max([m.deg() for m in BooleSet(treated)])
    if max_deg==0:
        max_deg=1
    i2deg=dict([(m2i[m],m.deg()) for m in BooleSet(treated)])
    polys_in_mat=[[m2i[t] for t in p.terms()] for p in polys_in_mat]
    polys_in_mat.sort(key=pkey)
    global mat_counter
    mat_counter=mat_counter+1
    import Image, ImageDraw, ImageColor
    
    rows=len(polys_in_mat)
    cols=len(m2i)
    im=Image.new("RGB",(cols,rows),"white")
    for i in xrange(len(polys_in_mat)):
        p=polys_in_mat[i]
        for j in p:
           assert i<rows
           assert j<cols
           im.putpixel((j,i), ImageColor.getrgb("hsl("+str(270-(270*i2deg[j])/max_deg)+",100%,50%)"))
    file_name=matrix_prefix+str(mat_counter)+".png"
    import os
    os.system("rm -f file_name")
    im.save(file_name)
    del im
    
    
    print "MATRIX_SIZE:", rows,"x",cols   
def add_reflection(im, bgcolor="#00000", amount=0.4, opacity=0.6):
    """ Returns the supplied PIL Image (im) with a reflection effect

    bgcolor  The background color of the reflection gradient
    amount   The height of the reflection as a percentage of the orignal image
    opacity  The initial opacity of the reflection gradient

    Originally written for the Photologue image management system for Django
    and Based on the original concept by Bernd Schlapsi

    """
    # convert bgcolor string to rgb value
    background_color = ImageColor.getrgb(bgcolor)

    # copy orignial image and flip the orientation
    reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM)

    # create a new image filled with the bgcolor the same size
    background = Image.new("RGB", im.size, background_color)

    # calculate our alpha mask
    start = int(255 - (255 * opacity))  # The start of our gradient
    steps = int(255 * amount)  # the number of intermedite values
    increment = (255 - start) / float(steps)
    mask = Image.new('L', (1, 255))
    for y in range(255):
        if y < steps:
            val = int(y * increment + start)
        else:
            val = 255
        mask.putpixel((0, y), val)
    alpha_mask = mask.resize(im.size)

    # merge the reflection onto our background color using the alpha mask
    reflection = Image.composite(background, reflection, alpha_mask)

    # crop the reflection
    reflection_height = int(im.size[1] * amount)
    reflection = reflection.crop((0, 0, im.size[0], reflection_height))

    # create new image sized to hold both the original image and the reflection
    composite = Image.new("RGB", (im.size[0], im.size[1] + reflection_height),
                          background_color)

    # paste the orignal image and the reflection into the composite image
    composite.paste(im, (0, 0))
    composite.paste(reflection, (0, im.size[1]))

    # return the image complete with reflection effect
    return composite
Example #30
0
 def render(self, im, bgcolor="#FFFFFF", amount=0.4, opacity=0.6):
     """ Returns the supplied PIL Image (im) with a reflection effect
 
     bgcolor  The background color of the reflection gradient
     amount   The height of the reflection as a percentage of the orignal image
     opacity  The initial opacity of the reflection gradient
 
     Originally written for the Photologue image management system for Django
     and Based on the original concept by Bernd Schlapsi
 
     """
     print "reflection filter"
     # convert bgcolor string to rgb value
     background_color = ImageColor.getrgb(bgcolor)
 
     # copy orignial image and flip the orientation
     reflection = im.copy().transpose(Image.FLIP_TOP_BOTTOM)
 
     # create a new image filled with the bgcolor the same size
     background = Image.new("RGB", im.size, background_color)
 
     # calculate our alpha mask
     start = int(255 - (255 * opacity)) # The start of our gradient
     steps = int(255 * amount) # the number of intermedite values
     increment = (255 - start) / float(steps)
     mask = Image.new('L', (1, 255))
     for y in range(255):
         if y < steps:
             val = int(y * increment + start)
         else:
             val = 255
         mask.putpixel((0, y), val)
     alpha_mask = mask.resize(im.size)
 
     # merge the reflection onto our background color using the alpha mask
     reflection = Image.composite(background, reflection, alpha_mask)
 
     # crop the reflection
     reflection_height = int(im.size[1] * amount)
     reflection = reflection.crop((0, 0, im.size[0], reflection_height))
 
     # create new image sized to hold both the original image and the reflection
     composite = Image.new("RGB", (im.size[0], im.size[1]+reflection_height), background_color)
 
     # paste the orignal image and the reflection into the composite image
     composite.paste(im, (0, 0))
     composite.paste(reflection, (0, im.size[1]))
 
     # return the image complete with reflection effect
     return composite
Example #31
0
def render_vector(geometry, img, bbox, coords, srs, color=None, renderer=None):
    """
    Renders a vector geometry on image.
    """
    if not color:
      color = config.geometry_color[geometry]
    if not renderer:
      renderer = config.default_vector_renderer
    bbox = projections.from4326(bbox, srs)
    lo1, la1, lo2, la2 = bbox
    coords = projections.from4326(coords, srs)
    W,H = img.size
    prevcoord = False
    coords = [((coord[0]-lo1)*(W-1)/abs(lo2-lo1), (la2-coord[1])*(H-1)/(la2-la1)) for coord in coords]

    if renderer == "cairo" and HAVE_CAIRO:
      "rendering as cairo"
      imgd = img.tostring()
      a = array.array('B',imgd)
      surface = cairo.ImageSurface.create_for_data (a, cairo.FORMAT_ARGB32, W, H, W*4)
      cr = cairo.Context(surface)
      cr.move_to(*coords[0])
      color = ImageColor.getrgb(color)
      cr.set_source_rgba(color[2], color[1], color[0], 1)
      if geometry == "LINESTRING" or geometry == "POLYGON":
        for k in coords:
          cr.line_to(*k)
      if geometry == "LINESTRING":
        cr.stroke()
      elif geometry == "POLYGON":
        cr.fill()
      elif geometry == "POINT":
        cr.arc(coords[0][0],coords[0][1],6,0,2*math.pi)
        cr.fill()
      img = Image.frombuffer("RGBA",( W,H ),surface.get_data(),"raw","RGBA",0,1)
    
    else:
      "falling back to PIL"
      coord = [(int(coord[0]),int(coord[1])) for coord in coords]                 # PIL dislikes subpixels
      draw = ImageDraw.Draw(img)
      if geometry == "LINESTRING":
        draw.line (coords, fill=color, width=3)
      elif geometry == "POINT":
        draw.ellipse((coords[0][0]-3,coords[0][1]-3,coords[0][0]+3,coords[0][1]+3),fill=color,outline=color)
      elif geometry == "POLYGON":
        draw.polygon(coords, fill=color, outline=color)
    return img
Example #32
0
    def linear_lum_hue(low, high, *args, **kwargs):
        '''linear_lum_hue(low, high) -> ColorMap

        returns a ColorMap that starts with 25% luminosity and blue at low and
        increases linearly in luminosity and hue to 75% and red at high.

        A better colormap would walk through the hues in some way that
        compensates for the fact that hues have different widths on a linear
        ramp---e.g., a large swath looks green.
        '''

        n = 10
        points = [ (val,) + col for val, col in zip(*[ np.linspace(low, high, num=n), 
            [ ImageColor.getrgb("hsl(%d,100%%,%d%%)" % (c % 360, l)) 
                for c,l in zip(np.linspace(350,600,num=n), np.linspace(60,25,num=n)) ][::-1] ]) ]

        return ColorMap(np.asarray(points))
Example #33
0
    def textfield_did_change(self, textfield):
        if textfield.text == '':
            textfield.text = '#'
        elif '##' in textfield.text:
            textfield.text = textfield.text.replace('##', '#')
        elif len(textfield.text) == 7:
            rgb = ImageColor.getrgb(textfield.text)
            r, g, b = rgb

            v = textfield.superview['groupView']

            v['slider1'].value = float(r) / 255
            v['slider2'].value = float(g) / 255
            v['slider3'].value = float(b) / 255

            v.superview.slider_action(v['slider1'])

        pass
Example #34
0
def crearImagenDireccionCorreo(usuarioActual):
	# Obteniendo los datos del usuario actual
	nombreUsuario = usuarioActual.username
	direccionCorreo = usuarioActual.email
	# Determinando el tamaño de la imagen
	longitudDireccionCorreo = len(direccionCorreo)
	anchoImagen = 13 + (longitudDireccionCorreo*7)
	# Creando la imagen de la direccion de correo
	imagenDireccionCorreo = Image.new('RGB', (anchoImagen,19), '#EEEEEE')
	dibujarImagen = ImageDraw.Draw(imagenDireccionCorreo)
	fuenteImagen = ImageFont.truetype(settings.RUTA_FNT+ 'weezer.ttf', 12)
	colorFuente = ImageColor.getrgb('#000000')
	dibujarImagen.text((3,0), direccionCorreo, font=fuenteImagen, fill=colorFuente)
	# Almacenando la imagen captcha generada
	imagenFinal = settings.RUTA_IMGDCE+nombreUsuario+ '.png'
	imagenFinal_nombre = 'dce/' +nombreUsuario+ '.png'
	imagenDireccionCorreo.save(imagenFinal, 'PNG')
	return imagenFinal_nombre
Example #35
0
    def from_hsl_file(filename, *args, **kwargs):
        '''from_hsl_file(filename) -> ColorMap

        reads the file as a list of control points specified as suitable for
        ImageColor.getrgb's hsl format, namely,
            value   hue     saturation   luminosity
        one per line and returns the appropriate ColorMap.

        TODO
        see from_file()
        '''

        points = []
        with open(filename) as inf:
            for line in inf:
                fields = line.split()
                points.append((float(fields[0]),) + ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % tuple(map(int, fields[1:]))))

        return ColorMap(np.asarray(points))
Example #36
0
def crearCaptcha():
	# Generando el codigo del captcha
	alfabetoElegido = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'
	textoImagen = ''.join([choice(alfabetoElegido) for i in range(5)])
	# Generando el codigo hash para el codigo captcha generado
	codigoImagen = sha.new(codigoSalt+textoImagen).hexdigest()
	# Determinando el tamaño de la imagen
	anchoImagen = 33 + (5*25)	
	# Creando la imagen del captcha
	imagenCaptcha = Image.new('RGB', (anchoImagen,47), '#EEEEEE')
	dibujarImagen = ImageDraw.Draw(imagenCaptcha)
	fuenteCaptcha = ImageFont.truetype(settings.RUTA_FNT+ 'nervous.ttf', 33)
	colorFuente = ImageColor.getrgb('#804000')
	dibujarImagen.text((3,0), textoImagen, font=fuenteCaptcha, fill=colorFuente)
	# Almacenando la imagen captcha generada
	captchaFinal = settings.RUTA_IMGTMP+codigoImagen+ '.png'
	captchaFinal_nombre = 'tmp/' +codigoImagen+ '.png'
	imagenCaptcha.save(captchaFinal, 'PNG')
	return codigoImagen, captchaFinal_nombre
Example #37
0
def makeImg(width=512, height=512, color='#ccc', text='placeholder',
            format='png'):
    '''Make a placeholder image.
    Args:
        width: The width of image in pixels.
        height: The height of image in pixels.
        color: Background color. See *The ImageColor Module* section in *Python
            Image Library Handbook*.
        text: Text in the middle of the image.
        format: See *Image File Formats* section in *Python Image Library
            Handbook*.
    Returns:
        Binary data of generated image.
    '''
    img = Image.new('RGBA', (width, height), color)
    draw = ImageDraw.Draw(img)
    fontSize = 32
    #Find the appropriate font size.
    while len(text):
        try:
            font = ImageFont.truetype(fontPath, fontSize)
        except IOError:
            raise IOError(
                'Can\'t load font file. Please set `fontPath` correctly.')
        textWidth, textHeight = draw.textsize(text, font=font)
        if textWidth > width or textHeight > height:
            fontSize /= 2
        else:
            break
    textLeft = (width - textWidth) / 2
    textTop = (height - textHeight) / 2
    if sum(ImageColor.getrgb(color)) < 255 * 3 / 2:
        textColor = 'White'
    else:
        textColor = 'Black'
    draw.text((textLeft, textTop), text, font=font, fill=textColor)
    #PIL Image -> Binary data
    fim = cStringIO.StringIO()
    img.save(fim, format)
    binData = fim.getvalue()
    fim.close()
    return binData
Example #38
0
    def decode(self, code):
        # decode the code
        middleType = self.MIDDLE_PATCH_SET[code & 0x03]
        middleInvert = (code >> 2) & 0x01
        cornerType = (code >> 3) & 0x0F
        cornerInvert = (code >> 7) & 0x01
        cornerTurn = (code >> 8) & 0x03
        sideType = (code >> 10) & 0x0F
        sideInvert = (code >> 14) & 0x01
        sideTurn = (code >> 15) & 0x03
        blue = (code >> 16) & 0x1F
        green = (code >> 21) & 0x1F
        red = (code >> 27) & 0x1F

        foreColor = (red << 3, green << 3, blue << 3)

        return (middleType, middleInvert, 0),\
               (cornerType, cornerInvert, cornerTurn),\
               (sideType, sideInvert, sideTurn),\
               foreColor, ImageColor.getrgb('white')
Example #39
0
    def decode(self, code):
        # decode the code
        middleType = self.MIDDLE_PATCH_SET[code & 0x03]
        middleInvert = (code >> 2) & 0x01
        cornerType = (code >> 3) & 0x0F
        cornerInvert = (code >> 7) & 0x01
        cornerTurn = (code >> 8) & 0x03
        sideType = (code >> 10) & 0x0F
        sideInvert = (code >> 14) & 0x01
        sideTurn = (code >> 15) & 0x03
        blue = (code >> 16) & 0x1F
        green = (code >> 21) & 0x1F
        red = (code >> 27) & 0x1F

        foreColor = (red << 3, green << 3, blue << 3)

        return (middleType, middleInvert, 0), \
               (cornerType, cornerInvert, cornerTurn), \
               (sideType, sideInvert, sideTurn), \
               foreColor, ImageColor.getrgb('white')
Example #40
0
 def decode(self, code):
     # decode the code  
     middleType  = self.MIDDLE_PATCH_SET[code & 0x03]
     middleInvert = (code >> 2) & 0x01
     cornerType  = (code >> 16) & 0x0F
     cornerInvert = (code >> 7) & 0x01
     cornerTurn  = (code >> 8) & 0x03
     sideType    = (code >> 10) & 0x0F
     sideInvert  = (code >> 14) & 0x01
     sideTurn    = (code >> 15) & 0x03
     blue        = 127 + (code % 100) # (code << 16) & 0x0F
     green       = 160 #(code >> 21) & 0x1F
     red         = 130 #(code >> 27) & 0x1F
     
     #foreColor = (red << 3, green << 3, blue << 3)
     foreColor = (red, green, blue)
     
     return (middleType, middleInvert, 0), \
            (cornerType, cornerInvert, cornerTurn), \
            (sideType, sideInvert, sideTurn), \
            foreColor, ImageColor.getrgb('#FFFFFF')
Example #41
0
def tobgr(x):
    """Convert a color to little-endian integer.  The PIL wants either
    a little-endian integer (0xBBGGRR) or a string (#RRGGBB).  weewx expects
    little-endian integer.  Accept any standard color format that is known
    by ImageColor for example #RGB, #RRGGBB, hslHSL as well as standard color
    names from X11 and CSS3.  See ImageColor for complete set of colors.
    """
    if isinstance(x, basestring):
        if x.startswith('0x'):
            return int(x, 0)
        try:
            (r,g,b) = ImageColor.getrgb(x)
            return r + g*256 + b*256*256
        except :
            pass
        try:
            return int(x)
        except ValueError:
            pass
        raise ValueError("Unknown color specifier: '%s'.  Colors must be specified as 0xBBGGRR, #RRGGBB, or standard color names." % x)
    return x
Example #42
0
 def decode(self, code):
     # decode the code  
     middleType  = self.MIDDLE_PATCH_SET[code & 0x03]
     middleInvert = (code >> 2) & 0x01
     cornerType  = (code >> 16) & 0x0F
     cornerInvert = (code >> 7) & 0x01
     cornerTurn  = (code >> 8) & 0x03
     sideType    = (code >> 10) & 0x0F
     sideInvert  = (code >> 14) & 0x01
     sideTurn    = (code >> 15) & 0x03
     blue        = 127 + (code % 100) # (code << 16) & 0x0F
     green       = 160 #(code >> 21) & 0x1F
     red         = 130 #(code >> 27) & 0x1F
     
     #foreColor = (red << 3, green << 3, blue << 3)
     foreColor = (red, green, blue)
     
     return (middleType, middleInvert, 0), \
            (cornerType, cornerInvert, cornerTurn), \
            (sideType, sideInvert, sideTurn), \
            foreColor, ImageColor.getrgb('#FFFFFF')
Example #43
0
    def __init__(self, eps_xx, eps_zz=None, mu=1.0, color='white', name=None):
        if eps_zz == None:
            eps_zz = eps_xx
        if callable(eps_xx):
            self.eps_xx = eps_xx
        else:
            self.eps_xx = lambda x: eps_xx

        if callable(eps_zz):
            self.eps_zz = eps_zz
        else:
            self.eps_zz = lambda x: eps_zz

        if callable(mu):
            self.mu = mu
        else:
            self.mu = lambda x: mu

        if callable(color):
            self.color = color
        else:
            self.color = lambda x: ImageColor.getrgb(color)
Example #44
0
    def __init__(self, eps_xx, eps_zz=None, mu=1.0, color='white', name=None):
        if eps_zz==None:
            eps_zz = eps_xx
        if callable(eps_xx):
            self.eps_xx = eps_xx
        else:
            self.eps_xx = lambda x: eps_xx

        if callable(eps_zz):
            self.eps_zz = eps_zz
        else:
            self.eps_zz = lambda x: eps_zz

        if callable(mu):
            self.mu = mu
        else:
            self.mu = lambda x: mu

        if callable(color):
            self.color = color
        else:
            self.color = lambda x: ImageColor.getrgb(color)
Example #45
0
    def decode(self, code):
        # decode the code        
        middleType  = self.MIDDLE_PATCH_SET[code & 0x03]
        middleInvert= (code >> 2) & 0x01
        cornerType  = (code >> 3) & 0x0F
        cornerInvert= (code >> 7) & 0x01
        cornerTurn  = (code >> 8) & 0x03
        sideType    = (code >> 10) & 0x0F
        sideInvert  = (code >> 14) & 0x01
        sideTurn    = (code >> 15) & 0x03
        blue        = (code >> 17) & 0x07
        green       = (code >> 20) & 0x07
        red         = (code >> 23) & 0x07

        # newly added for iconlang 
        mask        = (code >> 26) & 0xFF
        
        foreColor = (red << 5, green << 5, blue << 5)
        
        return (middleType, middleInvert, 0),\
               (cornerType, cornerInvert, cornerTurn),\
               (sideType, sideInvert, sideTurn),\
               foreColor, ImageColor.getrgb('white'), mask
Example #46
0
    def decode(self, code):
        # decode the code
        middleType = self.MIDDLE_PATCH_SET[code & 0x03]
        middleInvert = (code >> 2) & 0x01
        cornerType = (code >> 3) & 0x0F
        cornerInvert = (code >> 7) & 0x01
        cornerTurn = (code >> 8) & 0x03
        sideType = (code >> 10) & 0x0F
        sideInvert = (code >> 14) & 0x01
        sideTurn = (code >> 15) & 0x03
        blue = (code >> 17) & 0x07
        green = (code >> 20) & 0x07
        red = (code >> 23) & 0x07

        # newly added for iconlang
        mask = (code >> 26) & 0xFF

        foreColor = (red << 5, green << 5, blue << 5)

        return (middleType, middleInvert, 0),\
               (cornerType, cornerInvert, cornerTurn),\
               (sideType, sideInvert, sideTurn),\
               foreColor, ImageColor.getrgb('white'), mask
Example #47
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
Example #48
0
def make_hsv(value, hue, saturation=1, hue_smoothing=1, **kwargs):
    """Makes a color image based on two images of H and V in the HSV
    system."""

    if kwargs.has_key("alpha"):
        alpha = float(kwargs["alpha"])
    else:
        alpha = .3

    if kwargs.has_key("Q"):
        Q = float(kwargs["Q"])
    else:
        Q = 9

    m = 0

    (xs, ys) = value.shape

    # deal with nan
    # would be better to replace with median of surrounding pixels or something
    value = where(value != value, 0, value)
    hue = ndimage.gaussian_filter(hue, hue_smoothing)
    hue = where(hue != hue, 0, hue)

    if kwargs.has_key("vscale"):
        if kwargs["vscale"] == "auto":
            vscale = 30. / value.max()
            print "Autoscaling vscale=%e" % vscale
        else:
            vscale = float(kwargs["vscale"])
    else:
        vscale = 1

    if kwargs.has_key("hscale"):
        if kwargs["hscale"] == "auto":
            hscale = 30. / hue.max()
            print "Autoscaling hscale=%e" % hscale
        else:
            hscale = float(kwargs["hscale"])
    else:
        hscale = 1

    value = value * vscale + 1e-20
    value = value * arcsinh(alpha * Q * (value - m)) / (Q * value) * 100
    value = clip(value, 0, 100)

    hue = hue * hscale + 1e-20
    hue = hue * arcsinh(alpha * Q * (hue - m)) / (Q * hue) * 360
    hue = clip(hue, 0, 360)

    # now make the image by setting hsv values pixel by pixel
    img = Image.new("RGB", (xs, ys))
    pix = img.load()
    for x in range(xs):
        for y in range(ys):
            hsv = r"hsl(%d,%d%%,%d%%)" % (hue[x, y], saturation * 100,
                                          value[x, y])
            # intentinal transpose here
            pix[y, x] = ImageColor.getrgb(hsv)

    jpg = img.tostring("jpeg", "RGB")
    return jpg
Example #49
0
    def assembleBanner(self, name, medals, insignia):
        width, height = self.sizeBanner(name, medals, insignia)
        oheight = height

        bwidth = 4

        height = max(insignia.size[1] + 2 * bwidth, height)
        xpos = 2 * bwidth
        ypos = 2 * bwidth
        linesize = 16
        image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
        draw = ImageDraw.Draw(image)
        # Draw Border

        draw.rectangle([(0, bwidth), (width, height - (bwidth + 1))],
                       fill=ImageColor.getrgb(TRIM_COLOR))
        draw.rectangle([(bwidth, 0), (width - (bwidth + 1), height)],
                       fill=ImageColor.getrgb(TRIM_COLOR))
        draw.rectangle([(bwidth, 2 * bwidth),
                        (width - (bwidth + 1), height - 2 * (bwidth + 1))],
                       fill=ImageColor.getrgb(BG_COLOR))
        draw.rectangle([(2 * bwidth, bwidth),
                        (width - 2 * (bwidth + 1), height - (bwidth + 1))],
                       fill=ImageColor.getrgb(BG_COLOR))
        # Draw Name, Rank, Kills, Deaths, KD, Favorite Weapon, Rank
        image.paste(insignia, (width - (insignia.size[0] + 2 * bwidth),
                               height / 2 - insignia.size[1] / 2), insignia)
        namewidth, nameheight = self.yoster24.getsize(name)
        maxwidth = 525 - (2 * bwidth + insignia.size[0])
        fw, fh = self.yoster12.getsize(WATERMARK)
        if oheight == 50:
            #if it's just one line
            for medalset in medals:
                image.paste(medalset, (xpos, ypos), medalset)
                xpos += medalset.size[0] + 4

            if self.gold:
                draw.text((xpos, ypos),
                          name,
                          font=self.yoster24,
                          fill=GOLD_SHADOW)
                draw.text((xpos - 1, ypos - 1),
                          name,
                          font=self.yoster24,
                          fill=GOLD_COLOR)

            else:
                draw.text((xpos, ypos),
                          name,
                          font=self.yoster24,
                          fill=(155, 155, 155))
                draw.text((xpos - 1, ypos - 1),
                          name,
                          font=self.yoster24,
                          fill=(0xFF, 0xFF, 0xFF))

            draw.text((xpos + 2, height - 16),
                      WATERMARK,
                      font=self.yoster12,
                      fill=WATERMARK_COLOR)

        else:
            #if it's multiline
            ypos += linesize
            medalwidth = reduce(lambda x, y: x + y.size[0], medals, 0)

            if self.gold:
                draw.text((((width / 2) - (namewidth / 2)) + 1, 4 + 1),
                          name,
                          font=self.yoster24,
                          fill=GOLD_SHADOW)
                draw.text(((width / 2) - (namewidth / 2), 4),
                          name,
                          font=self.yoster24,
                          fill=GOLD_COLOR)

            else:
                draw.text((((width / 2) - (namewidth / 2)) + 1, 4 + 1),
                          name,
                          font=self.yoster24,
                          fill=(155, 155, 155))
                draw.text(((width / 2) - (namewidth / 2), 4),
                          name,
                          font=self.yoster24,
                          fill=(0xFF, 0xFF, 0xFF))

            #draw.text(,name,font=self.yoster24,fill=(155,155,155)) # text shadow
            #draw.text(,4),name,font=self.yoster24)
            ypos += 4
            spacing = 8
            xpos = bwidth + spacing
            for medalset in medals:
                if xpos + medalset.size[0] > maxwidth:
                    ypos += linesize + 2
                    xpos = bwidth
                image.paste(medalset, (xpos, ypos), medalset)

                xpos += medalset.size[0] + spacing
            draw.text(((width / 2) - (fw / 2), height - 16),
                      WATERMARK,
                      font=self.yoster12,
                      fill=WATERMARK_COLOR)

        #draw.text((14,height-16),"Dr. Frink's FUNHOUSE",font=yoster12,fill=(136,0,0))
        #draw.text((width-(fw+14),height-16),WATERMARK,font=yoster12,fill=(136,0,0))

        return image
Example #50
0
 def set_draw_color(self, color):
     super().set_draw_color(color)
     if type(color) is tuple:
         canvas.set_stroke_color(*color)
     else:
         canvas.set_stroke_color(*ImageColor.getrgb(color))
                y = 2 * x * y + y0
                x = xtemp
                xSqr = x * x
                ySqr = y * y
                i = i + 1
            iSpace[pixel_x][pixel_y] = i
    #Create histogram and total area underneath
    total = 0
    histogram = [0 for i in range(max_iteration + 1)]
    for x in range(0, width):
        for y in range(0, height):
            #print "Dealing with pixel ("+str(x)+","+str(y)+") with i-value "+str(iSpace[x][y])
            histogram[iSpace[x][y]] = histogram[iSpace[x][y]] + 1
            total = total + 1
    #Decide colour for each iteration value
    hue = [0.0 for i in range(max_iteration + 1)]
    for i in range(0, max_iteration):
        hue[i + 1] = hue[i] + (float(histogram[i + 1]) / float(total))
    print str(hue[max_iteration])
    #Colour in image
    for x in range(0, width):
        for y in range(0, height):
            pixels[x,
                   y] = ImageColor.getrgb("hsl(235,100%," +
                                          str(int(hue[iSpace[x][y]] * 100)) +
                                          "%)")
    #Save image
    img.save("ZoomOutput\output" + str(int(zoomLevel + 1)).zfill(3) + ".bmp")
    print "Image " + str(int(zoomLevel + 1)) + " complete"
    #time.sleep(3)
Example #52
0
def sepia(white="#fff0c0"):
    r, g, b = ImageColor.getrgb(white)
    r = _make_linear_lut(0, r)
    g = _make_linear_lut(0, g)
    b = _make_linear_lut(0, b)
    return ImagePalette("RGB", r + g + b)
Example #53
0
    startY = centerY - (rangeY / 2)
    for pixel_x in range(0, width):
        for pixel_y in range(0, height):
            x0 = 0.0
            y0 = 0.0
            x0 = (pixel_x * rangeX) / width + startX
            y0 = (pixel_y * rangeY) / height + startY
            if (pixel_y == 0 and pixel_x % 50 == 0):
                print "Pixels: (" + str(pixel_x) + "," + str(
                    pixel_y) + ") Coords: (" + str(x0) + "," + str(y0) + ")"
            x = 0.0
            y = 0.0
            xSqr = 0.0
            ySqr = 0.0
            i = -1
            while (xSqr + ySqr < 4 and i < max_iteration):
                xtemp = xSqr - ySqr + x0
                y = 2 * x * y + y0
                x = xtemp
                xSqr = x * x
                ySqr = y * y
                i = i + 1
            if i == max_iteration:
                i = 0
            pixels[pixel_x, pixel_y] = ImageColor.getrgb(
                "hsl(235,100%," +
                str(int(float(i) / float(max_iteration) * 100)) + "%)")
    img.save("ZoomOutput\output" + str(int(zoomLevel + 1)).zfill(3) + ".jpg")
    print "Image " + str(int(zoomLevel + 1)) + " complete"
    time.sleep(3)
Example #54
0
 def __init__(self, color, file, size=12):
     # FIXME: add support for bitmap fonts
     self.color = ImageColor.getrgb(color)
     self.font = ImageFont.truetype(file, size)
Example #55
0
 def __init__(self, color, opacity=255):
     self.color = ImageColor.getrgb(color)
Example #56
0
 def __init__(self, color, width=1, opacity=255):
     self.color = ImageColor.getrgb(color)
     self.width = width
Example #57
0
    def color_from_value(self, value):
        """ given a value between 0 and 1, return an (r,g,b) tuple """
 
        return ImageColor.getrgb("hsl(%d,%d%%,%d%%)" % (int( (1.0 - value) * 360 ), 80, 50))
Example #58
0
    def draw_chart(self, data, mstart, mend, outfilename, cellW, cellH,
                   verbose):
        # Calculate scale days
        scale_days = (mend - mstart).days
        pixels_per_day = cellW / 30

        titles = []
        monthdays = []
        cur = mstart
        while (cur <= mend):
            stitle = cur.strftime("%Y-%m")
            titles.append(stitle)
            monthdays.append((self.datefromstr(stitle) +
                              relativedelta(months=+1, days=-1)).day)
            cur = cur + relativedelta(months=+1)

        # Render graphic

        cols = len(titles)  # number of data columns
        rows = len(data)  # number of data rows
        #cellW = 80         # cell width
        #cellH = 20         # cell height
        lftColW = 150  # width of left column (task names)
        topRowH = 25  # height top row (month names)

        # calculate image size and define the canvas:
        imgH = topRowH + (cellH * rows)
        chartW = (sum(monthdays) * pixels_per_day)
        imgW = lftColW + chartW

        im = Image.new("RGBA", [imgW, imgH])

        draw = ImageDraw.Draw(im)

        ## color in the headers:
        fcolor = ImageColor.getrgb('gainsboro')

        draw.rectangle((0, 0, imgW, topRowH), fill=fcolor)
        draw.rectangle((0, 0, lftColW, imgH), fill=fcolor)

        # and the area where toprow and lftcol overlap:
        draw.rectangle((0, 0, lftColW, topRowH), fill="silver")

        ## draw the grid:
        xpos = 0
        x = 0
        for i in range(cols):
            xpos = monthdays[i] * pixels_per_day
            # range(lftColW, imgW, cellW):
            draw.line((x + lftColW, 0, x + lftColW, imgH), fill="black")
            x = x + xpos

        for y in range(topRowH, imgH, cellH):
            draw.line((0, y, imgW, y), fill="black")

        ## column titles, centered horizontally and vertically:
        ## font could be "arial.ttf"
        font_path = self.config.get('gantt', 'font_path')
        font = ImageFont.truetype(font_path, 12)

        x = 0
        for i in range(cols):
            xpos = monthdays[i] * pixels_per_day
            tsizeX, tsizeY = font.getsize(titles[i])
            draw.text(
                (
                    lftColW + x + (xpos - tsizeX) / 2,  # left
                    (topRowH - tsizeY)),  # top
                titles[i],
                font=font,
                fill="black")
            x = x + xpos

        now = datetime.now()
        if ((now - mstart).days > 0):
            ## draw "past" shading first, so it goes on bottom:
            draw.rectangle((lftColW, topRowH, lftColW +
                            ((now - mstart).days * pixels_per_day), imgH),
                           outline="black",
                           fill="lightgray")

        ## draw the charts:
        i = 0
        keylist = data.keys()
        keylist.sort()
        for k in keylist:
            # draw label left-aligned and approximately
            # centered vertically
            draw.text(
                (
                    5,  # left
                    topRowH + 5 + (i * cellH)),  # top	
                data[k]["title"],
                font=font,
                fill="black")

            rect = (
                lftColW +
                (data[k]["start_days"].days * pixels_per_day),  # left
                topRowH + (i * cellH),  # top
                lftColW + (data[k]["end_days"].days * pixels_per_day),  # right
                topRowH + ((i + 1) * cellH))  # bottom
            if (verbose):
                print data[k]["title"], rect

            # Draw task duration sized box
            if ("color" in data[k].keys()):
                colorname = data[k]["color"]
            else:
                colorname = "green"
            # colorname = data[k].keys()
            draw.rectangle(rect,
                           outline="black",
                           fill=ImageColor.getrgb(colorname))
            i = i + 1

        ## redraw outer border
        draw.rectangle((0, 0, imgW - 1, imgH - 1), outline="black")
        im.save(outfilename)
        draw = None
        im = None
Example #59
0
def render(text, fontalias, size=12, color="#000", rotation=0, bg_color=None):
    """Construct image from text.

    Returns a tuple with the image file path, width and height. Takes
    the parameters 'fontalias', 'size' (default 12), 'color' (default
    black) as CSS hex string, 'rotation' (default 0) which is the
    degrees to rotate the text counter-clockwise, and lastly
    'bg_color' (mostly useful when in GIF mode).

    The constructed image is stored in a cache under the media root in
    the RENDERTEXT_DIR set in settings.py (default is 'rendertext/').
    The font file to use is determined by mapping the fontalias
    through the RENDERTEXT_FONTMAP setting, a dictionary from
    fontalias strings to font file paths, e.g. {'verdana':
    '/home/django/fonts/verdana.ttf'}. RENDERTEXT_OUTPUT_FORMAT
    determines the output file format, either 'png' (default) or 'gif'."""

    # get settings
    render_dir = "rendertext/"
    if hasattr(settings, "RENDERTEXT_DIR"):
        render_dir = settings.RENDERTEXT_DIR

    fontmap = settings.RENDERTEXT_FONTMAP
    fontfile = fontmap[fontalias]

    gifmode = False
    if hasattr(settings, "RENDERTEXT_OUTPUT_FORMAT"):
        gifmode = settings.RENDERTEXT_OUTPUT_FORMAT == 'gif'

    # file path
    info = "|".join([text, fontalias, str(size), str(color), str(rotation)])
    name = md5.new(info.encode('utf-8')).hexdigest()

    extension = ".png"
    if gifmode:
        extension = ".gif"

    filepath = render_dir + name + extension

    # colors
    fg_color = ImageColor.getrgb(color)
    if not bg_color:
        if gifmode:
            bg_color = (255, 255, 255)
        else:
            bg_color = fg_color

    dim = (-1, -1)
    if not os.access(settings.MEDIA_ROOT + filepath, os.F_OK):
        # construct the image
        imf = ImageFont.truetype(fontfile, size)
        dim = imf.getsize(text)
        im = Image.new("RGBA", (dim[0] + 1, dim[1]), bg_color + (0, ))

        draw = ImageDraw.Draw(im)
        weird_font_renderer_fix = " "
        draw.text((1, 0),
                  text + weird_font_renderer_fix,
                  font=imf,
                  fill=fg_color)

        if rotation:
            if rotation == 90:
                im = im.transpose(Image.ROTATE_90)
            elif rotation == 180:
                im = im.transpose(Image.ROTATE_180)
            elif rotation == 270:
                im = im.transpose(Image.ROTATE_270)
            else:
                im = im.rotate(rotation, Image.BICUBIC, True)
            dim = im.size

        if not os.access(settings.MEDIA_ROOT + render_dir, os.F_OK):
            os.makedirs(settings.MEDIA_ROOT + render_dir)

        if gifmode:
            # unfortunately, PIL support for palette mode is rather
            # flaky so we have to hack it a bit

            oldim = im
            im = im.convert('P', dither=Image.NONE)

            # locate a good background color index
            hist = im.histogram()
            min_val = 1000000
            index = 0
            for i in range(0, len(hist)):
                if hist[i] < min_val:
                    min_val = hist[i]
                    index = i
                    if min_val == 0:
                        break

            # patch any fully transparent pixels
            src = oldim.load()
            dest = im.load()
            for y in range(0, dim[1]):
                for x in range(0, dim[0]):
                    if src[x, y][3] == 0:
                        dest[x, y] = index

            im.save(settings.MEDIA_ROOT + filepath, "GIF", transparency=index)
        else:
            im.save(settings.MEDIA_ROOT + filepath, "PNG")

    else:
        # read width and height
        im = Image.open(settings.MEDIA_ROOT + filepath)
        dim = im.size

    return (settings.MEDIA_URL + filepath, dim[0], dim[1])
Example #60
0
minY = -1.0
maxY = 1.0
rangeY = maxY - minY
max_iteration = 100
colour = [20, 125, 19]

img = Image.new('RGB', (width, height))
pixels = img.load()

for pixel_x in range(0, width - 1):
    for pixel_y in range(0, height - 1):
        x0 = 0.0
        y0 = 0.0
        x0 = (pixel_x * rangeX) / (width - 1) + minX
        y0 = (pixel_y * rangeY) / (height - 1) + minY
        print "Pixels: (" + str(pixel_x) + "," + str(
            pixel_y) + ") Coords: (" + str(x0) + "," + str(y0) + ")"
        x = 0.0
        y = 0.0
        i = -1
        while (x * x + y * y < 4 and i < max_iteration):
            xtemp = x * x - y * y + x0
            y = 2 * x * y + y0
            x = xtemp
            i = i + 1
        if i == 100:
            i = 0
        pixels[pixel_x,
               pixel_y] = ImageColor.getrgb("hsl(235,100%," + str(i) + "%)")

img.save("output.jpg")