def get(self): self.response.headers['Cache-Control'] = 'public, max-age=86400' self.response.headers['Content-Type'] = 'image/png' id = self.request.get('id', '.png')[:-4] img = memcache.get('/icon/png/' + id) if img: self.response.out.write(img) else: c = pngcanvas.PNGCanvas(32, 32) try: query = db.GqlQuery( 'SELECT * FROM WordIcon WHERE ANCESTOR is :1', id) w = query.fetch(1) except: query = db.GqlQuery( 'SELECT * FROM WordIcon WHERE ANCESTOR is :1', db.Key.from_path(*db.Key(id).to_path())) w = query.fetch(1) if w: data = w[0].icon for y in range(0, 16): for x in range(0, 16): z = x + y * 16 if z < len(data): c.color = colors[int(data[z])] c.rectangle(x * 2, y * 2, x * 2 + 1, y * 2 + 1) else: c.verticalGradient(0, 0, c.width - 1, c.height - 1, [0xff, 0, 0, 0xff], [0x20, 0, 0xff, 0x80]) img = c.dump() memcache.add('/icon/png/' + id, img) self.response.out.write(img)
def shp2png_poly(shape, outfile, iwidth=800, iheight=600): ''' shp2png_poly() - Convert a shapefile to a raster and save as a PNG file, filling in polygon holes Parameters ---------- shape : shapefile object outfile : str PNG image output file name iwidth : int, default=800 image width in pixels iheight : int, default=600 image height in pixels Returns ------- nothing ''' import iwfm as iwfm import pngcanvas as pngcanvas r = iwfm.shp_read(shapefile) # Setup the world to pixels conversion xdist = shp.bbox[2] - shp.bbox[0] ydist = shp.bbox[3] - shp.bbox[1] xratio = iwidth / xdist yratio = iheight / ydist polygons = [] for shape in shp.shapes(): # Loop through all parts to catch polygon holes! for i in range(len(shape.parts)): pixels = [] pt = None if i < len(shape.parts) - 1: pt = shape.points[shape.parts[i]:shape.parts[i + 1]] else: pt = shape.points[shape.parts[i]:] for x, y in pt: px = int(iwidth - ((shp.bbox[2] - x) * xratio)) py = int((shp.bbox[3] - y) * yratio) pixels.append([px, py]) polygons.append(pixels) c = pngcanvas.PNGCanvas(iwidth, iheight) for p in polygons: c.polyline(p) with open(outfile, 'wb') as f: f.write(c.dump()) f.close() return
def loadScheme(name, steps=255): ROOT_DIR = os.path.abspath(os.path.dirname(__file__)) file_loc = os.path.join(ROOT_DIR, 'color-schemes/' + name + '.png') f = open(file_loc, "rb") img = pngcanvas.PNGCanvas(24, steps, bgcolor=[0xff, 0xff, 0xff, TRANSPARENCY]) img.load(f) f.close() return img
def drawing(self, path, file, iwidth, iheight, first_field, tone): # Open the census shapefile inShp = shapefile.Reader(path + file.split('.')[0]) # Get the index of the population field first_index = None dots = [] for i, f in enumerate(inShp.fields): if f[0] == first_field: # Account for deletion flag first_index = i - 1 for sr in inShp.shapeRecords(): first = sr.record[first_index] density = first / 100 found = 0 while found < density: minx, miny, maxx, maxy = sr.shape.bbox x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) if self.point_in_poly(x, y, sr.shape.points): dots.append((x, y)) found += 1 # Set up the PNG output image c = pngcanvas.PNGCanvas(iwidth, iheight) r = int(tone[1:3], 16) b = int(tone[3:5], 16) g = int(tone[5:7], 16) # Draw the red dots c.color = (r, b, g, 0xff) for d in dots: x, y = self.world2screen(inShp.bbox, iwidth, iheight, *d) c.filled_rectangle(x - 1, y - 1, x + 1, y + 1) # Draw the census tracts c.color = (0, 0, 0, 0xff) for s in inShp.iterShapes(): pixels = [] for p in s.points: pixel = self.world2screen(inShp.bbox, iwidth, iheight, *p) pixels.append(pixel) c.polyline(pixels) # Save the image img_path = os.path.dirname(os.getcwd( )) + '/webGIS/static/dot_density/images/' + file.split('.')[0] + '.jpg' img = open(img_path, "wb") img.write(c.dump()) img.close() image = '/static/dot_density/images/' + file.split('.')[0] + '.jpg' return image
def create_png(r, g, b): """Create a PNG from r, g, b, data. RGB should be on the [-1.0, 1.0] scale. Returns: bytes: PNG image bytes """ r = round((r + 1) / 2 * 255) g = round((g + 1) / 2 * 255) b = round((b + 1) / 2 * 255) canvas = pngcanvas.PNGCanvas(150, 150, bgcolor=(r, g, b, 0xff)) data = canvas.dump() return data
def shp_to_png(shapefile_name, output_directory): """ Function to convert a shape file to png """ r = shapefile.Reader(shapefile_name) input_file_path, input_file_name = os.path.split(shapefile_name) input_file_name_prefix = str.split(input_file_name, '.')[0] # Determine bounding box x and y distances and then calculate an xyratio # that can be used to determine the size of the generated PNG file. A xyratio # of greater than one means that PNG is to be a landscape type image whereas # an xyratio of less than one means the PNG is to be a portrait type image. xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] xyratio = xdist / ydist # xyratio = 1 image_max_dimension = 1000 # Change this to desired max dimension of generated PNG if (xyratio >= 1): iwidth = image_max_dimension iheight = int(image_max_dimension / xyratio) else: iwidth = int(image_max_dimension / xyratio) iheight = image_max_dimension # Iterate through all the shapes within the shapefile and draw polyline # representations of them onto the PNGCanvas before saving the resultant canvas # as a PNG file xratio = iwidth / xdist yratio = iheight / ydist pixels = [] c = pngcanvas.PNGCanvas(iwidth, iheight) for shape in r.shapes(): for x, y in shape.points: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) c.polyline(pixels) pixels = [] f = open(output_directory + "%s.png" % input_file_name_prefix, "wb") f.write(c.dump()) f.close() return input_file_name_prefix + '.png', np.array([xdist, ydist])
def drawContours(self, path, file, iwidth, iheight, tone): # Open the contours r = shapefile.Reader(path + file.split('.')[0]) # Setup the world to pixels conversion xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] xratio = iwidth / xdist yratio = iheight / ydist contours = [] for shape in r.shapes(): for i in range(len(shape.parts)): pixels = [] pt = None if i < len(shape.parts) - 1: pt = shape.points[shape.parts[i]:shape.parts[i + 1]] else: pt = shape.points[shape.parts[i]:] for x, y in pt: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) contours.append(pixels) canvas = pngcanvas.PNGCanvas(iwidth, iheight) # PNGCanvas accepts rgba byte arrays for colors r = int(tone[1:3], 16) g = int(tone[3:5], 16) b = int(tone[5:7], 16) red = [r, g, b, 255] canvas.color = red # Loop through the polygons and draw them for c in contours: canvas.polyline(c) # Save the image img_path = os.path.dirname(os.getcwd( )) + '/webGIS/static/drawContours/images/' + file.split('.')[0] filePath = img_path + '.png' f = open(filePath, "wb") f.write(canvas.dump()) f.close() with Image.open(filePath) as im: im.convert('RGB').save(filePath[:-3] + 'jpg') image = '/static/drawContours/images/' + file.split('.')[0] + '.jpg' return image
def shp2Png(): r = shapefile.Reader("hancock.shp") xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] iwidth = 400 iheight = 600 xratio = iwidth / xdist yratio = iheight / ydist pixels = [] for x, y in r.shapes()[0].points: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) c = pngcanvas.PNGCanvas(iwidth, iheight) c.polyline(pixels) f = open("hancock_pngcvs.png", "wb") f.write(c.dump()) f.close()
def createPNGfromSHP(shapefile_name, outputFolder): filename = basename(shapefile_name) name, file_extension = os.path.splitext(filename) r = shapefile.Reader(shapefile_name) # Determine bounding box x and y distances and then calculate an xyratio # that can be used to determine the size of the generated PNG file. A xyratio # of greater than one means that PNG is to be a landscape type image whereas # an xyratio of less than one means the PNG is to be a portrait type image. xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] xyratio = xdist / ydist image_max_dimension = 400 # Change this to desired max dimension of generated PNG if (xyratio >= 1): iwidth = image_max_dimension iheight = int(image_max_dimension / xyratio) else: iwidth = int(image_max_dimension / xyratio) iheight = image_max_dimension # Iterate through all the shapes within the shapefile and draw polyline # representations of them onto the PNGCanvas before saving the resultant canvas # as a PNG file xratio = iwidth / xdist yratio = iheight / ydist pixels = [] c = pngcanvas.PNGCanvas(iwidth, iheight) # c.color = colors['background'] c.color = [0, 255, 0, 0] for shape in r.shapes(): for x, y in shape.points: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) c.polyline(pixels) pixels = [] f = file(outputFolder + "/" + name + ".png", "wb") f.write(c.dump()) f.close()
def createScheme(steps=255, r_start=255, g_start=255, b_start=255, r_step=-3.0, g_step=-1.0, b_step=-1.0): img = pngcanvas.PNGCanvas(30, steps) r_cur = r_start g_cur = g_start b_cur = b_start for y in range(0, steps): for x in range(0, 30): img.canvas[y][x] = [ r_cur, g_cur, b_cur, TRANSPARENCY] r_cur += r_step g_cur += g_step b_cur += b_step if r_cur > 255: r_step *= -1; r_cur = 255 + r_step; if r_cur < 0: r_step *= -1; r_cur = 0 + r_step; if g_cur > 255: g_step *= -1; g_cur = 255 + g_step; if g_cur < 0: g_step *= -1; g_cur = 0 + g_step; if b_cur > 255: b_step *= -1; b_cur = 255 + b_step; if b_cur < 0: b_step *= -1; b_cur = 0 + b_step; return img
def shp2png_empty(shape, outname, iwidth=400, iheight=600): ''' shp2png2() - Converts a shapefile to a raster and saves as a png file - just the outline with no fills Parameters ---------- shape : shapefile object outname : str output file name iwidth : int, default=400 image width in pixels iheight : int, default=600 image height in pixels Return ------ nothing ''' import pngcanvas as pngcanvas xdist = shape.bbox[2] - shape.bbox[0] ydist = shape.bbox[3] - shape.bbox[1] xratio = iwidth / xdist yratio = iheight / ydist pixels = [] for x, y in shape.shapes()[0].points: px = int(iwidth - ((shape.bbox[2] - x) * xratio)) py = int((shape.bbox[3] - y) * yratio) pixels.append([px, py]) c = pngcanvas.PNGCanvas(iwidth, iheight) c.polyline(pixels) f = open(outname, 'wb') f.write(c.dump()) f.close return
mapStrat(simEval(c, x, y)) for ((x, y), c) in zip(xys, childArgs) ] else: return [mapStrat(simEval([], x, y)) for (x, y) in xys] #def makeEvaluatorOld(jsonObj): # return { # 'num': (lambda jo: {'eval': (lambda this, x, y: [jo['val'] for i in range(0,3)])}), # 'x': (lambda jo: {'eval': (lambda this, x, y: [x for i in range(0,3)])}), # 'y': (lambda jo: {'eval': (lambda this, x, y: [y for i in range(0,3)])}), # 'atan': (lambda jo: {'c': [makeEvaluatorOld(jsonObj['ch'][0])], 'eval': (lambda this, x, y: [makeMappingStrategy(jo)(math.atan(v)) for v in this['c'][0]['eval'](this['c'][0], x,y)])}), # 'add': (lambda jo: {'c': [makeEvaluatorOld(jsonObj['ch'][0]), makeEvaluatorOld(jsonObj['ch'][1])], 'eval': (lambda this, x, y: [makeMappingStrategy(jo)(v1 + v2) for (v1,v2) in zip(this['c'][0]['eval'](this['c'][0],x,y), this['c'][1]['eval'](this['c'][1],x,y))])}), # }[jsonObj['t']](jsonObj) form = cgi.FieldStorage() func = jsonsinglequote.read(form.getfirst('f')) width = int(form.getfirst('w')) height = int(form.getfirst('h')) #if (form.getfirst('saveFunc') == 't'): # Don't do anything unreasonably large if (width <= 0 or height <= 0 or width > 10000 or height > 10000): pass else: c = pngcanvas.PNGCanvas(width, height) c.apply(makeTopEvaluator(func)) print("Content-type: image/png\n") print(c.dump())
# Rasterize a shapefile with PNGCanvas # https://github.com/GeospatialPython/Learning/raw/master/hancock.zip import shapefile import pngcanvas r = shapefile.Reader("hancock.shp") xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] iwidth = 400 iheight = 600 xratio = iwidth / xdist yratio = iheight / ydist pixels = [] for x, y in r.shapes()[0].points: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) c = pngcanvas.PNGCanvas(iwidth, iheight) c.polyline(pixels) f = open("hancock_pngcvs.png", "wb") f.write(c.dump()) f.close()
p1x, p1y = p2x, p2y return inside # Source shapefile - can be any polygon r = shapefile.Reader("GIS_CensusTract/GIS_CensusTract_poly.shp") # pixel to coordinate info xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] iwidth = 600 iheight = 500 xratio = iwidth / xdist yratio = iheight / ydist c = pngcanvas.PNGCanvas(iwidth, iheight, color=[255, 255, 255, 0xff]) # background color #c.filledRectangle(0, 0, iwidth, iheight) # Pen color c.color = [139, 137, 137, 0xff] # Draw the polygons for shape in r.shapes(): pixels = [] for x, y in shape.points: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) c.polyline(pixels)
def contour2png(source, target, iwidth=800, iheight=600): ''' contour2png() - Draw an entire contour shapefile to a pngcanvas image Parameters ---------- source : str input shapefile name target : str output PNG file name iwidth : int, default=800 image width in pixels iheight : int, default=600 image height in pixels Returns ------- nothing ''' import shapefile # pyshp import pngcanvas as pngcanvas if source[-4:] != '.shp': source += '.shp' if target[-4:] != '.png': target += '.png' r = shapefile.Reader(source) # Open the contour shapefile # Setup the world to pixels conversion xdist = r.bbox[2] - r.bbox[0] ydist = r.bbox[3] - r.bbox[1] xratio = iwidth / xdist yratio = iheight / ydist contours = [] # Loop through all shapes for shape in r.shapes(): # Loop through all parts for i in range(len(shape.parts)): pixels = [] pt = None if i < len(shape.parts) - 1: pt = shape.points[shape.parts[i]:shape.parts[i + 1]] else: pt = shape.points[shape.parts[i]:] for x, y in pt: px = int(iwidth - ((r.bbox[2] - x) * xratio)) py = int((r.bbox[3] - y) * yratio) pixels.append([px, py]) contours.append(pixels) # Set up the output canvas canvas = pngcanvas.PNGCanvas(iwidth, iheight) # PNGCanvas accepts rgba byte arrays for colors red = [0xFF, 0, 0, 0xFF] canvas.color = red # Loop through the polygons and draw them for c in contours: canvas.polyline(c) # Save the image f = open(target, 'wb') f.write(canvas.dump()) f.close() return
color.append(temp)''' temp = (val * 255 - 255 if (val > 0) else val * 255 + 255) temp = int(temp / 255) color = [] color.append(0) color.append(0) color.append(0) color.append(temp) return color adt = ADTFile() filename = raw_input("Please insert filename:\n") adt.read(filename) p = pngcanvas.PNGCanvas(144, 144) p.color = [0, 0, 0, 0xff] offsx = 0 offsy = 0 for i in range(16): for j in range(16): offsx = 9 * j offsy = 9 * i aposz = adt.mcnk[j * 16 + i].pos.z for x in range(9): for z in range(9): p.filledRectangle( offsx, offsy, offsx, offsy, floatToColor(adt.mcnk[j * 16 + i].mcvt.entries[x + 9 * z + 8 * z].value +
def density_plot(infile,fieldname,iwidth=600,iheight=400, denrat=100,savename=None): '''density_plot() - Read a shapefile and write it as an image Parameters ---------- infile : str source shapefile name fieldname : str field name for shading iwidth : int, default=600 image width in pixels iheight : str, default=400 image height in pixels denrat : int, default=100 density retio savename : str, default=None image destination file name (None = not saved) Returns ------- nothing ''' import shapefile # pyshp import pngcanvas as pngcanvas import world2screen import random inShp = shapefile.Reader(infile) val_index = None for i, f in enumerate(inShp.fields): # Get field index if f[0] == fieldname: val_index = i - 1 # Account for the Deletion Flag field dots = [] for shaperec in inShp.iterShapeRecords(): value = shaperec.record[val_index] # get value from field <fieldname> density = value / denrat found = 0 while found < density: minx, miny, maxx, maxy = shaperec.shape.bbox x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) if point_in_poly(x, y, shaperec.shape.points): dots.append((x, y)) found += 1 canvas = pngcanvas.PNGCanvas(iwidth, iheight) canvas.color = (255, 0, 0, 0xFF) # red dots for dot in dots: x, y = world2screen(inShp.bbox, iwidth, iheight, *dot) canvas.filled_rectangle(x - 1, y - 1, x + 1, y + 1) canvas.color = (0, 0, 0, 0xFF) # black lines for shape boundaries for shp in inShp.iterShapes(): pixels = [] for p in shp.points: pixel = world2screen(inShp.bbox, iwidth, iheight, *p) pixels.append(pixel) canvas.polyline(pixels) if savename: with open(savename, 'wb') as img: img.write(canvas.dump()) return