def eigendomprint(self): img=gd.image(self.SMALL) WHITE=img.colorAllocate(self.WHITE) BLACK=img.colorAllocate(self.BLACK) img.filledRectangle((0,0),(10,10),WHITE) LOGO=gd.image(self.LOGOFILE) LOGO.copyResizedTo(img,(0,0),(0,0),self.LOGOSMALLSIZE) img.string_ttf(self.FONT,40,0,(0,self.SMALL[1]-15),self.name,BLACK) img.string_ttf(self.FONT,20,0,(320, 23),"Don't Ask",BLACK) img.string_ttf(self.FONT,25,0,(320, 64),"☐ Look ",BLACK) img.string_ttf(self.FONT,25,0,(321, 65),"☐",BLACK) img.string_ttf(self.FONT,25,0,(320, 99),"☐ Hack ",BLACK) img.string_ttf(self.FONT,25,0,(321, 100),"☐",0) img.string_ttf(self.FONT,25,0,(320, 134),"☐ Repair ",BLACK) img.string_ttf(self.FONT,25,0,(321, 135),"☐",BLACK) img.string_ttf(self.FONT,25,0,(320, 169),"☐ Destroy ",BLACK) img.string_ttf(self.FONT,25,0,(321, 170),"☐",0) img.string_ttf(self.FONT,25,0,(320, 204),"☐ Steal ",BLACK) img.string_ttf(self.FONT,25,0,(321, 205),"☐",BLACK) img.string_ttf(self.FONT,25,0,(650, 64),"☐",BLACK) img.string_ttf(self.FONT,25,0,(651, 65),"☐",BLACK) img.string_ttf(self.FONT,25,0,(650, 99),"☐",BLACK) img.string_ttf(self.FONT,25,0,(651, 100),"☐",0) img.string_ttf(self.FONT,25,0,(650, 134),"☐",BLACK) img.string_ttf(self.FONT,25,0,(651, 135),"☐",BLACK) img.string_ttf(self.FONT,25,0,(650, 169),"☐",BLACK) img.string_ttf(self.FONT,25,0,(651, 170),"☐",0) img.string_ttf(self.FONT,25,0,(650, 204),"☐",BLACK) img.string_ttf(self.FONT,25,0,(651, 205),"☐",BLACK) img.writePng("data/output.png") os.system("convert -density 300 -units pixelsperinch data/output.png data/output.jpg") cups.Connection().printFile(self.printer,"data/output.jpg",title="Eigendom",options={'copies':str(self.copies),'page-ranges':'1'})
def FetchStitchedImage(self): """ Return a stitched image of all the points """ self.DownloadTiles() xrange = self.max_xtile - self.min_xtile yrange = self.max_ytile - self.min_ytile if (xrange == 0): xrange = 1 if (yrange == 0): yrange = 1 imgw = xrange * self.TILE_SIZE_PIXELS imgh = yrange * self.TILE_SIZE_PIXELS print "Allocating image ", imgw, "x", imgh img = gd.image((imgw, imgh), 1) if self.url != None: for x in range(self.min_xtile, self.max_xtile): for y in range(self.min_ytile, self.max_ytile): tileimg = gd.image(self.cachedir + "/" + str(self.zoom) + "/" + str(x) + "/" + str(y) + "." + self.tiletype) xpos = (x - self.min_xtile) * self.TILE_SIZE_PIXELS ypos = (y - self.min_ytile) * self.TILE_SIZE_PIXELS tileimg.copyTo(img, (xpos, ypos)) else: rectclr = img.colorAllocate((255, 255, 255)) img.rectangle((0, 0), (imgw, imgh), rectclr, rectclr) return img
def gd_scale(filename, width, height): im = gd.image(filename) newim = gd.image((width, height)) size = im.size() im.copyPaletteTo(newim) im.copyResampledTo(newim, (0, 0), (0, 0), (width, height), (size[0], size[1])) newim.writeJpeg('outgd.jpg', 95)
def foodprint(self): img=gd.image(self.SMALL) WHITE=img.colorAllocate(self.WHITE) BLACK=img.colorAllocate(self.BLACK) img.filledRectangle((0,0),(10,10),WHITE) LOGO=gd.image(self.LOGOFILE) LOGO.copyResizedTo(img,(0,0),(0,0),self.LOGOSMALLSIZE) img.string_ttf(self.FONT,40,0,(0,self.SMALL[1]-15),self.name,BLACK) img.string_ttf(self.FONT,50,0,(320, 120),time.strftime('%Y-%m-%d'),BLACK) img.writePng("data/foodout.png") os.system("convert -density 300 -units pixelsperinch data/foodout.png data/foodout.jpg") cups.Connection().printFile(self.printer,"data/foodout.jpg",title="Voedsel",options={'copies': str(self.copies),'page-ranges':'1'})
def main(): """Initial entry point""" # Build the temp images and fill with stop color image = gd.image(DIMENSIONS, True) filler = image.colorAllocate((167, 167, 167)) image.fill((0, 0), filler) # Write pixels to image based on input text coords = set_pixels_by_text(image) # Copy the temp image to a smaller image of the appropriate height smaller = gd.image((DIMENSIONS[0], coords[1] + 1), True) image.copyTo(smaller, (0, 0), (0, 0), (DIMENSIONS[0], coords[1] + 1)) smaller.writePng('files/book.png')
def generatePic(text): data = array.array('c') img = gd.image((128, 16)) white = img.colorAllocate((255, 255, 255)) img.string_ttf("cour", 14, 0, (0,12), text, white) pic=open("xx.bmp","w") img.writeWbmp(pic) pic.close() picFile = open("xx.bmp","rb") picFile.seek(5) #skip bmp header try: data.fromfile(picFile, 989) except EOFError: print "Less data" data.byteswap() return data
def generatePic(text): data = array.array('c') img = gd.image((128, 16)) white = img.colorAllocate((255, 255, 255)) img.string_ttf("cour", 14, 0, (0, 12), text, white) pic = open("xx.bmp", "w") img.writeWbmp(pic) pic.close() picFile = open("xx.bmp", "rb") picFile.seek(5) #skip bmp header try: data.fromfile(picFile, 989) except EOFError: print "Less data" data.byteswap() return data
def generate_rnaseq_graph(urlx, filename, out_clr, geneid, start, end): xvalues = [] values = [] #output += "<br/>GENERATING RNA SEQ GRAPH! colour = " + str(hex_to_rgb(out_clr)) #output += "Chr%s :: %s-%s url = %s" %(chromosome, start, end, urlx) #output += "<br/><br/>urlx = " + "mpileups/"+urlx + "; out = " + filename + "<br/><br/>" if urlx == "": return match = re.search(REGEX, urlx) if match: filename2 = match.group(2) + "_" + geneid try: for read in open("mpileups/"+geneid+"/"+urlx): #output +=("<br/>{0}".format(float(read.split('\t')[1]))) #output +=("x = {0}, y = {1}<br/>".format(float(read.split('\t')[1]), float(int(read.split('\t')[3]) - read.split('\t')[4].count('<') - read.split('\t')[4].count('>')))) xvalues.append(float(read.split('\t')[1])) values.append(float(int(read.split('\t')[3]) - read.split('\t')[4].count('<') - read.split('\t')[4].count('>'))) values = [int(x / Y_AXIS_CEILING * RNA_IMG_HEIGHT) for x in values] # Scale all values rnaseqgraph = gd.image((RNA_IMG_WIDTH, RNA_IMG_HEIGHT)) white = rnaseqgraph.colorAllocate((255,255,255)) green = rnaseqgraph.colorAllocate(hex_to_rgb(out_clr)) for i in range(len(xvalues)): #output +=("x = {0} ---> reactangle({1}, {2}, {3}, {4})<br/>".format(xvalues[i], int(float(xvalues[i] - start) /(end-start) * RNA_IMG_WIDTH), RNA_IMG_HEIGHT, int(float(xvalues[i] - start)/(end-start) * RNA_IMG_WIDTH), RNA_IMG_HEIGHT - values[i])) rnaseqgraph.rectangle((int(float(xvalues[i] - start) /(end-start) * RNA_IMG_WIDTH), RNA_IMG_HEIGHT), (int(float(xvalues[i] - start)/(end-start) * RNA_IMG_WIDTH), RNA_IMG_HEIGHT - values[i]), green) f = open(filename, "w+") rnaseqgraph.writePng(f) f.close() except pysam.SamtoolsError as msg: output += "<br/><br/>pysam.SamtoolsError was raised for locus = " + geneid + " in experiment = " + match.group(2) + " BAM file. ERR MSG >>>" + str(msg) + "<br/>"
def __init__( self, fontsize = 10, angle = 0, sizeX = 700, limit = 10 , nbQuery = None): self.fontsize = fontsize self.angle = angle self.limit = limit self.nbQuery = nbQuery self.recX = self.limit + (self.fontsize*10) self.pixY = 2*self.fontsize self.nbligne = 1 self.sizeX = sizeX self.sizeY = self.estimatSizeY() self.picture = gd.image( ( self.sizeX+self.recX+2*self.limit, self.sizeY ) ) self.color = {'white' : self.picture.colorAllocate( (255, 255, 255) ), 'grey': self.picture.colorAllocate( (125, 125, 125) ), 'lightgrey': self.picture.colorAllocate( (211, 211, 211) ), 'green' : self.picture.colorAllocate( (0,205,0) ), 'lightgreen' : self.picture.colorAllocate( (152,251,152) ), 'orange' : self.picture.colorAllocate( (255,187,0) ), 'blue' : self.picture.colorAllocate( (0, 0, 255) ), 'lightblue' : self.picture.colorAllocate( (0, 100, 200) ), 'red' : self.picture.colorAllocate( (255, 0, 0) ), 'lightred' : self.picture.colorAllocate( (255, 128, 128) ), 'pink' : self.picture.colorAllocate( (255, 0, 255) ), 'yellow' : self.picture.colorAllocate( (255, 255, 0) ), 'black' : self.picture.colorAllocate( (0, 0, 0) ) }
def build_animated_frames(images): """Builds several images that will be compiled into an animated GIF""" for i in range(0, FRAMES): im1 = gd.image(DIMENSIONS, True) images[0]['img'].copyTo(im1, (0, 0), (X_OFFSET, 0), DIMENSIONS) im2 = gd.image(DIMENSIONS, True) images[1]['img'].copyTo(im2, (0, 0), (X_OFFSET, 0), DIMENSIONS) for j in range(0, DIMENSIONS[1] / FRAMES): images[1]['img'].copyTo(im1, (0, j * FRAMES), (X_OFFSET, j * FRAMES), (DIMENSIONS[0], i + 1)) images[0]['img'].copyTo(im2, (0, j * FRAMES), (X_OFFSET, j * FRAMES), (DIMENSIONS[0], i + 1)) im1.writePng(SAVE_DIR + '/anim' + str(i) + '.png') im2.writePng(SAVE_DIR + '/anim' + str(i + FRAMES) + '.png')
def border(req, style, rgb): import gd rgb = tuple(map(lambda x: int(x, 16), (rgb[0:2], rgb[2:4], rgb[4:6]))) try: width = int(req.GET.get('w', 228)) except (ValueError, TypeError): width = 228 try: height = int(req.GET.get('h', 1)) except (ValueError, TypeError): height = 1 if width < 1 or height < 1: raise Http404 if rgb != (0, 0, 0): # if line is black, then use white(#FFFFF) as background color backcolor = (255, 255, 255) else: backcolor = (0, 0, 0) # TODO # check display width img = gd.image((width, height)) back = img.colorAllocate(backcolor) img.colorTransparent(back) color = img.colorAllocate(rgb) if style == 'dotted': pattern = (color, color, back, back) elif style == 'dashed': pattern = (color, color, color, back, back, back) else: # solid pattern = (color,) img.setStyle(pattern) for y in xrange(height): img.line((0, y), (width, y), gd.gdStyled) fp = StringIO() img.writeGif(fp) content = fp.getvalue() fp.close() content_type = 'image/gif' res = HttpResponse(content, content_type=content_type) res['Content-Type'] = content_type res['Content-Length'] = str(len(content)) res['ETag'] = '"%s"' % md5(content).hexdigest() res['Last-Modified'] = http_date() res['Expires'] = http_date(time.time() + CACHE_TIMEOUT) patch_cache_control(res, max_age=CACHE_TIMEOUT) return res
def border(req, style, rgb): import gd rgb = tuple(map(lambda x: int(x, 16), (rgb[0:2], rgb[2:4], rgb[4:6]))) try: width = int(req.GET.get('w', 228)) except (ValueError, TypeError): width = 228 try: height = int(req.GET.get('h', 1)) except (ValueError, TypeError): height = 1 if width < 1 or height < 1: raise Http404 if rgb != (0, 0, 0): # if line is black, then use white(#FFFFF) as background color backcolor = (255, 255, 255) else: backcolor = (0, 0, 0) # TODO # check display width img = gd.image((width, height)) back = img.colorAllocate(backcolor) img.colorTransparent(back) color = img.colorAllocate(rgb) if style == 'dotted': pattern = (color, color, back, back) elif style == 'dashed': pattern = (color, color, color, back, back, back) else: # solid pattern = (color, ) img.setStyle(pattern) for y in xrange(height): img.line((0, y), (width, y), gd.gdStyled) fp = StringIO() img.writeGif(fp) content = fp.getvalue() fp.close() content_type = 'image/gif' res = HttpResponse(content, content_type=content_type) res['Content-Type'] = content_type res['Content-Length'] = str(len(content)) res['ETag'] = '"%s"' % md5(content).hexdigest() res['Last-Modified'] = http_date() res['Expires'] = http_date(time.time() + CACHE_TIMEOUT) patch_cache_control(res, max_age=CACHE_TIMEOUT) return res
def draw_net_bar(fname, outfname=None): fname = os.path.join(fname, "interface", "if_octets-eth0.rrd") try: values = rrdtool.fetch(fname, "AVERAGE")[2][-20:] except rrdtool.error: values = [(0.0, 0.0)] v = [x for x in values if x[0] is not None and x[1] is not None] if not v: # Fallback in case we only get NaNs v = [(0.0, 0.0)] rx_value, tx_value = v[-1] # Convert to bits rx_value = rx_value * 8 / 10 ** 6 tx_value = tx_value * 8 / 10 ** 6 max_value = (int(max(rx_value, tx_value) / 50) + 1) * 50.0 image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT)) border_color = image.colorAllocate(settings.BAR_BORDER_COLOR) white = image.colorAllocate((0xFF, 0xFF, 0xFF)) background_color = image.colorAllocate(settings.BAR_BG_COLOR) tx_line_color = image.colorAllocate((0x00, 0xA1, 0x00)) rx_line_color = image.colorAllocate((0x00, 0x00, 0xA1)) image.rectangle((0, 0), (settings.WIDTH - 1, settings.HEIGHT - 1), border_color, background_color) image.rectangle( (1, 1), (int(tx_value / max_value * (settings.WIDTH - 2)), settings.HEIGHT / 2 - 1), tx_line_color, tx_line_color, ) image.rectangle( (1, settings.HEIGHT / 2), (int(rx_value / max_value * (settings.WIDTH - 2)), settings.HEIGHT - 2), rx_line_color, rx_line_color, ) image.string_ttf( settings.FONT, 8.0, 0.0, (settings.WIDTH + 1, settings.HEIGHT - 1), "TX/RX: %.2f/%.2f Mbps" % (tx_value, rx_value), white, ) io = StringIO() image.writePng(io) io.seek(0) data = io.getvalue() io.close() return data
def make_image(): """Builds an image from a sequence of nucleic acids""" global nucleic_acids # Chromosome from Project Gutenberg's Human Genome Project files: # http://www.gutenberg.org/ebooks/subject/15882 # See README.md for details last = (iter * max + max) if last > TOTAL: last = TOTAL - 1 f = codecs.open(pwd + "chromosome01.txt", "r", "utf-8") f.seek(979) chromosome = f.read(max) f.close() # Create new image img = gd.image((px * size, px * size)) # Fill it with a background color bg = img.colorAllocate((255, 255, 255)) img.fill((0, 0), bg) # Assign colors from nucleic_acids hash to image colors # Apparently can't do this on the fly for each acid because # there seems to be a limit on the number of times one can # do this per image? colors = {} for n in nucleic_acids.keys(): colors[n] = img.colorAllocate(nucleic_acids[n]["color"]) # Counters i = 0 j = 0 for c in chromosome: c = c.upper() # Increment rows if we're at the end of one if i >= px: i = 0 j += 1 # If we're past the max number of rows, quit if j >= px: break # Increment acid count and place rectangle on the image nucleic_acids[c]["count"] = nucleic_acids[c]["count"] + 1 img.filledRectangle((i * size, j * size), (i * size + size - 1, j * size + size - 1), colors[c]) i += 1 # Write the resulting image img.writePng(pwd + "chrom.png")
def Main(): form = cgi.FormContent() label = form["label"][0] im = gd.image(base_pic) # im = mk_image(im) print 'Content-type: image/gif \n\n' print im
def generate(self): """Build and write the PNG file""" img = gd.image((self.width, self.height)) # allocate the background as "white", but set it to be transparent bgColorIndex = img.colorAllocate(self.backgroundColor) stippleColorIndex = img.colorAllocate(self.stippleColor) img.colorTransparent(bgColorIndex) # set up the stipple pattern stipple = gd.image((2, 2)) stippleBgColorIndex = stipple.colorAllocate(self.backgroundColor) stippleFgColorIndex = stipple.colorAllocate(self.stippleColor) stipple.colorTransparent(stippleBgColorIndex) stipple.setPixel((0, 0), stippleFgColorIndex) stipple.setPixel((1, 1), stippleFgColorIndex) # draw the stippled background img.setTile(stipple) img.filledRectangle((1, 1), (self.width - 2, self.height - 2), gd.gdTiled) # draw the now box nowBoxColorIndex = img.colorAllocate(self.nowBoxColor) img.rectangle((self.nowXCoord, 1), (self.nowXCoord + self.nowBoxWidth, self.height - 2), nowBoxColorIndex) img.fillToBorder((self.nowXCoord + 1, 2), nowBoxColorIndex, bgColorIndex) # draw the border if the cell is "on" if self.onCell: borderColorIndex = img.colorAllocate(self.borderColor) img.rectangle((1, 0), (self.width - 1, self.height - 1), borderColorIndex) # write out the file outputFile = open(self.filename, "w") img.writePng(outputFile) outputFile.close() return
def generate(self): """Build and write the PNG file""" img = gd.image((self.width, self.height)) # allocate the background as "white", but set it to be transparent bgColorIndex = img.colorAllocate(self.backgroundColor) stippleColorIndex = img.colorAllocate(self.stippleColor) img.colorTransparent(bgColorIndex) # set up the stipple pattern stipple = gd.image((2,2)) stippleBgColorIndex = stipple.colorAllocate(self.backgroundColor) stippleFgColorIndex = stipple.colorAllocate(self.stippleColor) stipple.colorTransparent(stippleBgColorIndex) stipple.setPixel((0,0), stippleFgColorIndex) stipple.setPixel((1,1), stippleFgColorIndex) # draw the stippled background img.setTile(stipple) img.filledRectangle((1,1), (self.width-2, self.height-2), gd.gdTiled) # draw the now box nowBoxColorIndex = img.colorAllocate(self.nowBoxColor) img.rectangle( (self.nowXCoord, 1), (self.nowXCoord + self.nowBoxWidth, self.height - 2), nowBoxColorIndex) img.fillToBorder((self.nowXCoord+1, 2), nowBoxColorIndex, bgColorIndex) # draw the border if the cell is "on" if self.onCell: borderColorIndex = img.colorAllocate(self.borderColor) img.rectangle((1,0), (self.width-1, self.height-1), borderColorIndex) # write out the file outputFile = open(self.filename, "w") img.writePng(outputFile) outputFile.close() return
def gen_base_image( self, res_str ): origin_gd = gd.image( self._image_arg.get_origin_size() ) self.set_random_black_ground( origin_gd ) origin_gd.string(gd.gdFontGiant, get_rand_origin_position( self._image_arg.get_origin_position_range() ), \ str( res_str ), origin_gd.colorAllocate(get_rand_deep_color(self._deep_color_red, self._deep_color_green, \ self._deep_color_blue)) ) self.set_rand_line( origin_gd ) return origin_gd
def Main(tmpfile, yeer, start_month, end_month, start_day, end_day, str_title, data_code): im = gd.image(iowa_gif_src) # load image into a gd container im = mk_image(im, yeer, start_month, end_month, start_day, end_day, str_title) start_tuple = (int(yeer), int(start_month), int(start_day), 0, 0, 0, 0, 0, 0) end_tuple = (int(yeer), int(end_month), int(end_day), 0, 0, 0, 0, 0, 0) start_secs = time.mktime(start_tuple) end_secs = time.mktime(end_tuple) if start_secs > end_secs: style.SendError("Go back and check your dates.") days = int((end_secs - start_secs)/86400) i = 0 # loop variable for station in stations: tot = 0 for day in range(0, days+1): this_sec = start_secs + (86400 * day) local = time.localtime(this_sec) year = time.strftime("%Y", local) month = time.strftime("%m", local) day = time.strftime("%d", local) sation = station+"_"+year dateStr = month+"-"+day+"-"+year try: query = mydb2.query("SELECT "+data_code+" from "+station+"_"+yeer+" WHERE date(day) = '"+dateStr+"' ").getresult() query.sort() except: continue try: high = int(float(query[0][0])) # radiation low = int(float(query[23][0])) # radiation except: Hello = "Hi" if low < 50: # The low is always at least 50 low = 50 if high > 86: high = 86 if high < 50: # If the high is lower than 50, than no Gdd's this_gdd = 0 else: this_gdd = ((high+low)/2) - 50 tot = tot + this_gdd im = plot_pt(im, int( float(tot)), locations[i]) # my ploting function i = i + 1 # Increment variable im.writeGif(tmpfile) # Write file out
def newImage(size): x,y,z = size img = gd.image( ((x+1)*unit, (y+1)*unit) ) colors = { 'white': img.colorAllocate((255,255,255)), 'black': img.colorAllocate((0,0,0)), 'red': img.colorAllocate((255,0,0)), 'blue': img.colorAllocate((0,0,255)), 'green': img.colorAllocate((0,255,0)), 'gray': img.colorAllocate((200,200,200)), } img.filledRectangle((0,0),(x*unit,y*unit), colors['white']) return img, colors
def newImage(size): x,y = size img = gd.image( ((x+1)*unit, (y+1)*unit) ) colors = { 'white': img.colorAllocate((255,255,255)), 'black': img.colorAllocate((0,0,0)), 'red': img.colorAllocate((255,0,0)), 'blue': img.colorAllocate((0,0,255)), 'green': img.colorAllocate((0,255,0)), 'gray': img.colorAllocate((200,200,200)), } img.filledRectangle((0,0),(x*unit,y*unit), colors['white']) return img, colors
def build_image(self): """Builds an image from some text""" self.coords = [0, 0] self.image = gd.image(self.DIMENSIONS, True) # Build the temp images and fill with stop color filler = self.image.colorAllocate((0, 0, 0)) self.image.fill((0, 0), filler) self.set_pixels_by_text() self.save_image()
def most_least_cited( self, width ): """This is the only function using gd, so we handle it more directly for now. """ image = gd.image((10*width, 10)) image.filledRectangle((0,0),(10*width-1, 10), image.colorAllocate((255,0,0))) buffer = cStringIO.StringIO() image.writePng(buffer) data = buffer.getvalue() buffer.close() return data
def generate_exon_graph(map_info, start, end): exongraph = gd.image((EXON_IMG_WIDTH, EXON_IMG_HEIGHT)) white = exongraph.colorAllocate((255,255,255)) black = exongraph.colorAllocate((0,0,0)) blue = exongraph.colorAllocate((0,0,255)) exongraph.lines(((0, EXON_IMG_HEIGHT), (EXON_IMG_WIDTH, EXON_IMG_HEIGHT)), black) for region in map_info[u'result']: if region[u'type'] == u'exon': #output += (float(region[u'start'] - start) /(end-start), float(region[u'end'] - start)/(end-start)) exongraph.filledRectangle((int(float(region[u'start'] - start) /(end-start) * EXON_IMG_WIDTH), EXON_IMG_HEIGHT), (int(float(region[u'end'] - start)/(end-start) * EXON_IMG_WIDTH), 0), blue) f = open("multi_exongraph.png", "w") exongraph.writePng(f) f.close()
def draw_net_bar(fname, outfname=None): fname = os.path.join(fname, "interface", "if_octets-eth0.rrd") try: values = rrdtool.fetch(fname, "AVERAGE")[2][-20:] except rrdtool.error: values = [(0.0, 0.0)] v = [x for x in values if x[0] is not None and x[1] is not None] if not v: # Fallback in case we only get NaNs v = [(0.0, 0.0)] rx_value, tx_value = v[-1] # Convert to bits rx_value = rx_value * 8 / 10**6 tx_value = tx_value * 8 / 10**6 max_value = (int(max(rx_value, tx_value) / 50) + 1) * 50.0 image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT)) border_color = image.colorAllocate(settings.BAR_BORDER_COLOR) white = image.colorAllocate((0xff, 0xff, 0xff)) background_color = image.colorAllocate(settings.BAR_BG_COLOR) tx_line_color = image.colorAllocate((0x00, 0xa1, 0x00)) rx_line_color = image.colorAllocate((0x00, 0x00, 0xa1)) image.rectangle((0, 0), (settings.WIDTH - 1, settings.HEIGHT - 1), border_color, background_color) image.rectangle((1, 1), (int(tx_value / max_value * (settings.WIDTH - 2)), settings.HEIGHT / 2 - 1), tx_line_color, tx_line_color) image.rectangle((1, settings.HEIGHT / 2), (int(rx_value / max_value * (settings.WIDTH - 2)), settings.HEIGHT - 2), rx_line_color, rx_line_color) image.string_ttf(settings.FONT, 8.0, 0.0, (settings.WIDTH + 1, settings.HEIGHT - 1), "TX/RX: %.2f/%.2f Mbps" % (tx_value, rx_value), white) io = StringIO() image.writePng(io) io.seek(0) data = io.getvalue() io.close() return data
def simple(): im = gd.image((20,200)) white = im.colorAllocate((255, 255, 255)) black = im.colorAllocate((0, 0, 0)) #im.colorTransparent(white) im.interlace(1) im.string_ttf(FONT, 10.0, 1.56, (15, 190), sys.argv[1], black) f=open(sys.argv[1]+".png","w") im.writePng(f) f.close()
def build_jumble(images): """Builds a jumbled image from two boxarts""" im = gd.image(DIMENSIONS, True) k = 0 for i in range(0, (DIMENSIONS[0] / SQUARE_SIZE)): for j in range(0, (DIMENSIONS[1] / SQUARE_SIZE)): images[k % 2]['img'].copyTo(im, (i * SQUARE_SIZE, j * SQUARE_SIZE), (i * SQUARE_SIZE + X_OFFSET, j * SQUARE_SIZE), (SQUARE_SIZE, SQUARE_SIZE)) k += 1 k += 1 im.writePng(SAVE_DIR + '/jumble.png')
def get_authentication_picture( self, str_array, result_size=None ): tmp_gd = gd.image( [self._image_arg.get_origin_size()[0] * len(str_array), self._image_arg.get_origin_size()[1]] ) for i in xrange(len(str_array)): tmp = self.gen_base_image( str_array[i] ) tmp.copyResizedTo( tmp_gd, ( self._image_arg.get_origin_position()[0] + self._image_arg.get_origin_size()[0] * i, \ self._image_arg.get_origin_position()[1] ), self._image_arg.get_origin_position(), \ self._image_arg.get_origin_size(), self._image_arg.get_origin_size() ) tmp = None if result_size != None: result_gd = gd.image( result_size ) tmp_gd.copyResizeTo( result_gd, self._image_arg.get_origin_position(), self._image_arg.get_origin_position(), \ tmp_gd.size(), result_size ) else: result_gd = tmp_gd ios = StringIO() result_gd.writeJpeg(ios , self._image_arg.get_quality()) tmp = ios.getvalue() ios.close() return tmp
def simple(): im = gd.image((20, 200)) white = im.colorAllocate((255, 255, 255)) black = im.colorAllocate((0, 0, 0)) #im.colorTransparent(white) im.interlace(1) im.string_ttf(FONT, 10.0, 1.56, (15, 190), sys.argv[1], black) f = open(sys.argv[1] + ".png", "w") im.writePng(f) f.close()
def simple(): im = gd.image((200, 200)) white = im.colorAllocate((255, 255, 255)) black = im.colorAllocate((0, 0, 0)) red = im.colorAllocate((255, 0, 0)) blue = im.colorAllocate((0, 0, 255)) im.colorTransparent(white) im.interlace(1) im.rectangle((0,0),(199,199),black) im.arc((100,100),(195,175),0,360,blue) im.fill((100,100),red) print im.get_bounding_rect(FONT, 12.0, 0.0, (10, 100), "Hello Python") im.string_ttf(FONT, 20.0, 0.0, (10, 100), "Hello Python", black) f=open("xx.png","w") im.writePng(f) f.close() f=open("xx.jpg", "w") im.writeJpeg(f,100) f.close() f=cStringIO.StringIO() im.writePng(f) print "PNG size:", len(f.getvalue()) f.close() f = urllib2.urlopen("http://www.gnu.org/graphics/gnu-head-sm.jpg") im = gd.image(f, "jpg") f.close() print "GNU Image Size:", im.size()
def test(): img = gd.image((640, 480)) white = img.colorAllocate((255, 255, 255)) black = img.colorAllocate((0, 0, 0)) red = img.colorAllocate((255, 0, 0)) blue = img.colorAllocate((0, 0, 255)) green = img.colorAllocate((0, 255, 0)) img.filledRectangle((0, 0), (640, 480), white) img.line((0, 0), (640, 480), red) img.string(gd.gdFontLarge, (20, 240), "Hello World", black) img.rectangle((20 - 2, 240 - 2), (20 + 20, 240 + 20), blue) img.writeGif("test.gif")
def test(): img = gd.image((640,480)) white = img.colorAllocate((255,255,255)) black = img.colorAllocate((0,0,0)) red = img.colorAllocate((255,0,0)) blue = img.colorAllocate((0,0,255)) green = img.colorAllocate((0,255,0)) img.filledRectangle((0,0),(640,480),white) img.line((0,0),(640,480),red) img.string( gd.gdFontLarge, (20,240), "Hello World", black ) img.rectangle( (20-2,240-2),(20+20,240+20), blue) img.writeGif("test.gif")
def simple(): im = gd.image((200, 200)) white = im.colorAllocate((255, 255, 255)) black = im.colorAllocate((0, 0, 0)) red = im.colorAllocate((255, 0, 0)) blue = im.colorAllocate((0, 0, 255)) im.colorTransparent(white) im.interlace(1) im.rectangle((0, 0), (199, 199), black) im.arc((100, 100), (195, 175), 0, 360, blue) im.fill((100, 100), red) print im.get_bounding_rect(FONT, 12.0, 0.0, (10, 100), "Hello Python") im.string_ttf(FONT, 20.0, 0.0, (10, 100), "Hello Python", black) f = open("xx.png", "w") im.writePng(f) f.close() f = open("xx.jpg", "w") im.writeJpeg(f, 100) f.close() f = cStringIO.StringIO() im.writePng(f) print "PNG size:", len(f.getvalue()) f.close() f = urllib2.urlopen("http://www.gnu.org/graphics/gnu-head-sm.jpg") im = gd.image(f, "jpg") f.close() print "GNU Image Size:", im.size()
def plotPopcon(popcon, outfile): log_basis = 10 y_scale = 10 popcon_max = max(popcon.values()) size = (len(popcon), 5*y_scale) heap = [] # get a sorted version for pkg in popcon: heappush(heap, (popcon[pkg], pkg)) # now print the ranking ranks = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} while heap: (pop, pkg) = heappop(heap) rank = 0 #rank = int((5 * pop / popcon_max)) if pop > 0: rank = 5*log(pop,log_basis)/log(popcon_max, log_basis) ranks[int(rank)+1] += 1 for i in ranks: print i,ranks[i] # allocate image data img = gd.image(size) img.colorAllocate((255,255,255)) # draw it i = 0 last_rank = 0 heap = [] # get a sorted version for pkg in popcon: heappush(heap, (popcon[pkg], pkg)) while heap: (pop, pkg) = heappop(heap) rank = 1 if pop > 0: #pop = int(log(pop,log_basis))+1 rank = int(5*log(pop,log_basis)/log(popcon_max, log_basis))+1 img.line((i-1, size[1]-(last_rank*y_scale)), (i, size[1]-(rank*y_scale)), 1) i+=1 last_rank = rank img.writePng(outfile)
def create_text_image(text, f, font=gd.gdFontLarge): """ Create image with text. ``text`` is the text which should be printed to the image and ``f`` is an open file-like object. The resulting image is written to ``f`` in PNG format. """ text_width, text_height = gd.fontstrsize(font, text) img = gd.image((text_width + 2, text_height + 2)) black = img.colorAllocate((0, 0, 0)) white = img.colorAllocate((255, 255, 255)) img.fill((0, 0), white) img.string(font, (1, 1), text, black) img.writePng(f)
def draw(self): """ Draw to a gd image and return the image instance """ left, bottom, width, height = self.figure.bbox.get_bounds() im = gd.image((int(width), int(height))) if not hasattr(im, 'setAntiAliased'): gd_requirements_failed() renderer = RendererGD(im, self.figure.dpi) self.figure.draw(renderer) renderer.finish() return im
def draw(self): """ Draw to a gd image and return the image instance """ left, bottom, width, height = self.figure.bbox.get_bounds() im = gd.image((int(width), int(height))) if not hasattr(im, 'setAntiAliased'): raise RuntimeError('gd_requirements_failed') renderer = RendererGD(im, self.figure.dpi) self.figure.draw(renderer) renderer.finish() return im
def parse(self, *args, **kwargs): """Loads and parses a BML file. See parent for more doc.""" kwargs = explode_kwargs(kwargs) try: duration = kwargs['duration'] except: duration = 1000.0 try: invert = kwargs['invert'] except: invert = False # Load image image = gd.image(kwargs['filepath']) frames = [] (framew, frameh) = image.size() frame = numpy.zeros((framew, frameh), dtype=int) colormap = {} # Convert image to brightness values for x in xrange(framew): for y in xrange(frameh): i = image.getPixel((x, y)) # Add new colors to colormap if i not in colormap: (r, g, b) = image.colorComponents(i) colormap[i] = (r + g + b) * 99 / (3 * 255) # Invert color if invert: colormap[i] = math.fabs(colormap[i] - 99) # Fill array with brightness values frame[x][y] = colormap[i] # Frame done frames.append((duration, frame)) # Movie done return frames
def load_terrain(self, file) : "build terrain triangles from an image that gd can read" import gd im = gd.image(file) width, height = im.size() # scale the terrain sx, sy, sz = 4, 4, 4 coords = [ # terrain spread from -5.0 to +5.0 ( (x - width / 2) * sx, (y - height / 2) * sy, im.red(im.getPixel((x,y))) / 255.0 * sz ) for x in range(width) for y in range(height) ] grid = {} verts = [] for (x,y,z) in coords : grid[(x,y)] = len(verts) # index into verts verts.append((x,y,z)) faces = [] for (x,y,z) in coords : if x >= sx * (width / 2 - 1) or y >= sy * (height / 2 - 1) : continue # 1 - 2 # | / | <-- how triangles are built out of quads # 3 - 4 p1 = (x, y) p2 = (x + sx, y) p3 = (x, y + sy) p4 = (x + sx, y + sy) # triangles are groups of three indices faces.append((grid[p1], grid[p2], grid[p3])) faces.append((grid[p2], grid[p3], grid[p4])) self.terrain = { "verts" : verts, "faces" : faces, } mesh = ode.TriMeshData() mesh.build(verts, faces) self.terrain_geom = ode.GeomTriMesh(mesh, self.space) self.terrain_geom.setPosition((0.0,0.0,0.0))
def draw_cpu_bar(fname, outfname=None): fname = os.path.join(fname, "cpu", "virt_cpu_total.rrd") try: values = rrdtool.fetch(fname, "AVERAGE")[2][-20:] except rrdtool.error: values = [(0.0, )] v = [x[0] for x in values if x[0] is not None] if not v: # Fallback in case we only get NaNs v = [0.0] # Pick the last value value = v[-1] image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT)) border_color = image.colorAllocate(settings.BAR_BORDER_COLOR) white = image.colorAllocate((0xff, 0xff, 0xff)) background_color = image.colorAllocate(settings.BAR_BG_COLOR) if value >= 90.0: line_color = image.colorAllocate((0xff, 0x00, 0x00)) elif value >= 75.0: line_color = image.colorAllocate((0xda, 0xaa, 0x00)) else: line_color = image.colorAllocate((0x00, 0xa1, 0x00)) image.rectangle((0, 0), (settings.WIDTH - 1, settings.HEIGHT - 1), border_color, background_color) image.rectangle((1, 1), (int(value / 100.0 * (settings.WIDTH - 2)), settings.HEIGHT - 2), line_color, line_color) image.string_ttf(settings.FONT, 8.0, 0.0, (settings.WIDTH + 1, settings.HEIGHT - 1), "CPU: %.1f%%" % value, white) io = StringIO() image.writePng(io) io.seek(0) data = io.getvalue() io.close() return data
def get_imgdata(imgfile, indent): try: img = gd.image(imgfile) except IOError as e: PrintLog.message( u'unable to open image file: {0:s} because: {1:s}'.format( imgfile, e)) return (0, 0, r'') (width, height) = img.size() if width <= (LCD_WIDTH - LCD_IMG_MARGIN - indent): is_black = lambda x, y: (0, 0, 0) == img.colorComponents( img.getPixel((x, y))) h_range = range(0, width) v_range = range(0, height) elif height <= (LCD_WIDTH - LCD_IMG_MARGIN - indent): is_black = lambda x, y: (0, 0, 0) == img.colorComponents( img.getPixel((y, x))) v_range = range(0, width) h_range = range(height - 1, -1, -1) (width, height) = (height, width) else: PrintLog.message(u'image file: {0:s} is too big'.format(imgfile)) return (0, 0, r'') data = '' for v in v_range: byte = 0 bit_count = 8 for h in h_range: if is_black(h, v): pixel = 1 else: pixel = 0 bit_count -= 1 byte |= pixel << bit_count if 0 == bit_count: data += struct.pack('<B', byte) byte = 0 bit_count = 8 if 8 != bit_count: data += struct.pack('<B', byte) return (width, height, data)
def __init__(self, width, height): self.__image = gd.image((width, height)) self.__xOffset = 0 self.__height = height self.diamondWidth = 7 """Width of any diamonds rendered.""" self.diamondLeftMargin = 2 """Width of horizontal margin on the left side a diamond""" self.diamondVerticalMargin = 0 """Height of vertical margin above and below a diamond""" self.diamondColor = (0xff, 0xff, 0xff) """Color used to render diamonds.""" return
def draw_cpu_bar(fname, outfname=None): fname = os.path.join(fname, "cpu", "virt_cpu_total.rrd") try: values = rrdtool.fetch(fname, "AVERAGE")[2][-20:] except rrdtool.error: values = [(0.0, )] v = [x[0] for x in values if x[0] is not None] if not v: # Fallback in case we only get NaNs v = [0.0] # Pick the last value value = v[-1] image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT)) border_color = image.colorAllocate(settings.BAR_BORDER_COLOR) white = image.colorAllocate((0xff, 0xff, 0xff)) background_color = image.colorAllocate(settings.BAR_BG_COLOR) if value >= 90.0: line_color = image.colorAllocate((0xff, 0x00, 0x00)) elif value >= 75.0: line_color = image.colorAllocate((0xda, 0xaa, 0x00)) else: line_color = image.colorAllocate((0x00, 0xa1, 0x00)) image.rectangle((0, 0), (settings.WIDTH - 1, settings.HEIGHT - 1), border_color, background_color) image.rectangle( (1, 1), (int(value / 100.0 * (settings.WIDTH - 2)), settings.HEIGHT - 2), line_color, line_color) image.string_ttf(settings.FONT, 8.0, 0.0, (settings.WIDTH + 1, settings.HEIGHT - 1), "CPU: %.1f%%" % value, white) io = StringIO() image.writePng(io) io.seek(0) data = io.getvalue() io.close() return data
def plotPopcon(popcon, outfile): log_basis = 10 y_scale = 10 popcon_max = max(popcon.values()) size = (len(popcon), 5 * y_scale) heap = [] # get a sorted version for pkg in popcon: heappush(heap, (popcon[pkg], pkg)) # now print the ranking ranks = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} while heap: (pop, pkg) = heappop(heap) rank = 0 #rank = int((5 * pop / popcon_max)) if pop > 0: rank = 5 * log(pop, log_basis) / log(popcon_max, log_basis) ranks[int(rank) + 1] += 1 for i in ranks: print i, ranks[i] # allocate image data img = gd.image(size) img.colorAllocate((255, 255, 255)) # draw it i = 0 last_rank = 0 heap = [] # get a sorted version for pkg in popcon: heappush(heap, (popcon[pkg], pkg)) while heap: (pop, pkg) = heappop(heap) rank = 1 if pop > 0: #pop = int(log(pop,log_basis))+1 rank = int( 5 * log(pop, log_basis) / log(popcon_max, log_basis)) + 1 img.line((i - 1, size[1] - (last_rank * y_scale)), (i, size[1] - (rank * y_scale)), 1) i += 1 last_rank = rank img.writePng(outfile)
def writeColorSwatch(color, filename): """Write a 1x1 png of the given color. color -- an RGB tuple filename -- name of the PNG file """ image = gd.image((1, 1)) # all we have to do is allocate the background color; no need to draw # anything in the foreground image.colorAllocate(color) # write the file file = open(filename, "w") image.writePng(file) file.close() return
def drawDividers(startPoint, colorTuple): """Draw vertical timeline dividers once per self.intervalSize.""" brush = gd.image((self.dividerWidth, 1)) # set up the colors backgroundColorIndex = brush.colorAllocate(self.backgroundColor) colorIndex = brush.colorAllocate(colorTuple) brush.colorTransparent(backgroundColorIndex) # set up the pattern brush.setPixel((0, 0), colorIndex) brush.setPixel((self.dividerWidth - 1, 0), colorIndex) self.__img.setBrush(brush) # draw the lines i = startPoint while i <= self.width: self.__img.line((i, 0), (i, self.height - 1), gd.gdBrushed) i = i + self.intervalSize
def render_image(file, levels, zoom): img = gd.image(file) def pixel_value(row,col): c = (img.colorComponents(img.getPixel((row,col)))) # get RGB c = (c[0] + c[1] + c[2]) / 3 # Grayscale return int(c), levels - c * (float(levels - 1) / 256.0) - 1 # grayscale, normalized w, h = img.size() surf = pygame.Surface((w * zoom, h * zoom)) arr = [] for i in xrange(0, h): arr.append([]) for j in xrange(0, w): arr[i].append([]) c, arr[i][j] = pixel_value(j,i) pygame.draw.rect(surf, (c,c,c), (j * zoom, i * zoom, zoom, zoom)) return surf, arr, w, h
def make_files(pagename): redfilename = "/tmp/Red-%s" % pagename greenfilename = "/tmp/Green-%s" % pagename bluefilename = "/tmp/Blue-%s" % pagename # create a small test image. gd.gdMaxColors = 256 i = gd.image((200, 100)) black = i.colorAllocate((0, 0, 0)) white = i.colorAllocate((255, 255, 255)) red = i.colorAllocate((255, 55, 55)) green = i.colorAllocate((55, 255, 55)) blue = i.colorAllocate((55, 55, 255)) # now write a red version i.rectangle((0, 0), (199, 99), red, red) i.line((0, 0), (199, 99), black) i.string(gd.gdFontLarge, (5, 50), pagename, white) i.writePng(redfilename) # now write a green version i.rectangle((0, 0), (199, 99), green, green) i.line((0, 0), (99, 99), black) i.string(gd.gdFontLarge, (5, 50), pagename, white) i.writePng(greenfilename) # write a blue version i.rectangle((0, 0), (199, 99), blue, blue) i.line((0, 0), (99, 199), black) i.string(gd.gdFontLarge, (5, 50), pagename, white) i.writePng(bluefilename) # propose that we delete it (in case it exists) t.go(host + "index.php?title=File:%s&action=delete" % pagename) # make sure that we've NOT gotten the wrong page and HAVE gotten the right one. t.notfind('You are about to delete the file') t.find("could not be deleted") return (redfilename, greenfilename, bluefilename)
def render(self, s): self.projectMercator() img = gd.image((s,s)) img.origin((0,s-1),1,-1) bg = img.colorAllocate((255,255,255)) img.colorTransparent(bg) ink = img.colorAllocate((0,0,0)) xMax = s - 1 yMax = s - 1 tx = (xMax - self.sx * xMax) / 2 ty = (yMax - self.sy * yMax) / 2 points = map(lambda p: (int(tx + self.sx * round(p[0] * xMax)), int(round(ty + self.sy * p[1] * yMax))), self.projPoints) img.lines(points, ink) return img
def __init__(self, width, height, nowStartXCoord): """Initialize a background object. width -- width of the background height -- height of the background nowStartXCoord --- starting X coordinate of the 'now' bar """ self.width = width self.height = height self.nowStartXCoord = nowStartXCoord self.dividerWidth = 8 """Number of pixels between left and right vertical divider lines""" self.intervalSize = 100 """Number of pixels representing a single interval""" self.nowColor = (0x99, 0x99, 0xcc) """Color of the 'now' bar""" self.nowWidth = 10 """Number of pixels wide to make the 'now' bar""" self.stippleColor = (0x99, 0x99, 0x99) """Color to use in the stippling pattern for the 'future' section""" self.backgroundColor = (0xff, 0xff, 0xff) """(R,G,B) tuple of background color.""" self.darkDividerColor = (0xaa, 0xaa, 0xaa) """(R,G,B) tuple of dark divider color.""" self.lightDividerColor = (0xdd, 0xdd, 0xdd) """(R,G,B) tuple of light divider color.""" self.__img = gd.image((width, height)) return
outf = files.pop(0) # drop program name outf = files.pop(0) if len(files) == 1: # convenience function to use next file as 2nd input m = re.match(r"(.*?)(\d+)(\.png)$", files[0]) files.append(m.group(1) + ("%04d" % (int(m.group(2)) + 1)) + m.group(3)) #print files, outf if len(files) != 2: print "usage: mergepics.py outimg img1 img2" exit(1) sys.stderr.write("processing image " + files[0] + "\n") imgs = [] for f in files: img = gd.image(f) imgs.append(img) xy = imgs[0].size() if crop > 0: img = gd.image((xy[0] - crop, xy[1]), True) imgs[0].copyTo(img, (0, 0), (0, 0), (xy[0] - crop, xy[1])) imgs[0] = img img = gd.image((xy[0] - crop, xy[1]), True) imgs[1].copyTo(img, (0, 0), (crop, 0), (xy[0] - crop, xy[1])) imgs[1] = img xy = imgs[0].size() for y in range(0, xy[1] - 1):
li = [1, 2, 3] li2 = [4, 5, 6] for x in li2: li.append(x) [li.append(x) for x in li2] print li print buildConnectionString(myParams) gd.gdMaxColors = 1 img = gd.image((128, 16)) black = img.colorAllocate((0, 0, 0)) white = img.colorAllocate((255, 255, 255)) #img.gdMaxColors(256) img.rectangle((2, 2), (10, 10), white) print "hallo" test = StringIO.StringIO() test.write("lala") f = open("xx.bmp", "w")
fname = os.path.join(RRD_PREFIX, os.path.basename(hostname), "cpu", "virt_cpu_total.rrd") try: values = rrdtool.fetch(fname, "AVERAGE")[2][-20:] except rrdtool.error, e: #raise InternalError(str(e)) values = [(0.0, )] v = [x[0] for x in values if x[0] is not None] if not v: # Fallback in case we only get NaNs v = [0.0] # Pick the last value value = v[-1] image = gd.image((IMAGE_WIDTH, HEIGHT)) border_color = image.colorAllocate(BAR_BORDER_COLOR) white = image.colorAllocate((0xff, 0xff, 0xff)) background_color = image.colorAllocate(BAR_BG_COLOR) if value >= 90.0: line_color = image.colorAllocate((0xff, 0x00, 0x00)) elif value >= 75.0: line_color = image.colorAllocate((0xda, 0xaa, 0x00)) else: line_color = image.colorAllocate((0x00, 0xa1, 0x00)) image.rectangle((0,0), (WIDTH-1, HEIGHT-1), border_color, background_color) image.rectangle((1,1), (int(value/100.0 * (WIDTH - 2)), HEIGHT - 2), line_color, line_color) image.string_ttf(FONT, 8.0, 0.0, (WIDTH + 1, HEIGHT - 1), "CPU: %.1f%%" % value, white)