def nasty_rgb_via_png_paint(self, cairo_format, has_alpha : bool, img_data, x : int, y : int, width : int, height : int, rowstride : int, rgb_format): log.warn("nasty_rgb_via_png_paint%s", (cairo_format, has_alpha, len(img_data), x, y, width, height, rowstride, rgb_format)) #PIL fallback from PIL import Image if has_alpha: oformat = "RGBA" else: oformat = "RGB" #use frombytes rather than frombuffer to be compatible with python3 new-style buffers #this is slower, but since this codepath is already dreadfully slow, we don't care bdata = memoryview_to_bytes(img_data) src_format = rgb_format.replace("X", "A") try: img = Image.frombytes(oformat, (width,height), bdata, "raw", src_format, rowstride, 1) except ValueError as e: log("PIL Image frombytes:", exc_info=True) raise Exception("failed to parse raw %s data as %s to %s: %s" % ( rgb_format, src_format, oformat, e)) from None #This is insane, the code below should work, but it doesn't: # img_data = bytearray(img.tostring('raw', oformat, 0, 1)) # pixbuf = new_from_data(img_data, COLORSPACE_RGB, True, 8, width, height, rowstride) # success = self.cairo_paint_pixbuf(pixbuf, x, y) #So we still rountrip via PNG: from io import BytesIO png = BytesIO() img.save(png, format="PNG") reader = BytesIO(png.getvalue()) png.close() img = ImageSurface.create_from_png(reader) self.cairo_paint_surface(img, x, y, width, height, {}) return True
def __init__(self, w=10, h=10, path=''): self._w, self._h = w, h surface = ImageSurface.create_from_png(path) self._imgpat = SurfacePattern(surface) self._imgpat.set_filter(FILTER_BEST) scaler = Matrix() scaler.scale(surface.get_width() / w, surface.get_height() / h) self._imgpat.set_matrix(scaler)
def __init__ (self, imagePaths): gtk.DrawingArea.__init__(self) self.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.BUTTON_PRESS_MASK) self.connect("expose-event", self.draw) self.connect("button_press_event", self.buttonPress) self.surfaces = [ImageSurface.create_from_png(path) for path in imagePaths] self.current = 0 width, height = self.surfaces[0].get_width(), self.surfaces[0].get_height() self.size = gtk.gdk.Rectangle(0, 0, width, height) self.set_size_request(width, height)
def __init__ (self, imagePaths): GObject.GObject.__init__(self) self.set_events(Gdk.EventMask.EXPOSURE_MASK | Gdk.EventMask.BUTTON_PRESS_MASK) self.connect("draw", self.draw) self.connect("button_press_event", self.buttonPress) self.surfaces = [ImageSurface.create_from_png(path) for path in imagePaths] self.current = 0 width, height = self.surfaces[0].get_width(), self.surfaces[0].get_height() self.size = (0, 0, width, height) self.set_size_request(width, height)
def get_mmap_image(mmap): """ Render a Map to an ImageSurface. """ handle, filename = mkstemp(suffix=".png") try: close(handle) mmap.draw(fatbits_ok=True).save(filename) img = ImageSurface.create_from_png(filename) finally: unlink(filename) return img
def get_mmap_image(mmap): """ Render a Map to an ImageSurface. """ handle, filename = mkstemp(suffix='.png') try: close(handle) mmap.draw(fatbits_ok=True).save(filename) img = ImageSurface.create_from_png(filename) finally: unlink(filename) return img
def __init__(self, image_paths): GObject.GObject.__init__(self) self.set_events(Gdk.EventMask.EXPOSURE_MASK | Gdk.EventMask.BUTTON_PRESS_MASK) self.connect("draw", self.draw) self.connect("button_press_event", self.buttonPress) self.surfaces = [ImageSurface.create_from_png(path) for path in image_paths] self.current = 0 width, height = self.surfaces[0].get_width(), self.surfaces[ 0].get_height() self.size = (0, 0, width, height) self.set_size_request(width, height)
def resize(img,widget): def progress(): name=img.split("/")[-1] im1=Image.open(tmp+name+"scaled.png") x=cx.get_text() im2=im1.crop((int(x),0,int(x)+240,400)) im2.save(tmp+name+"resized.jpg") widget.set_from_file(tmp+name+"resized.jpg") control() w.destroy() def move_rectangle(): x=im.get_pointer()[0] cr=im.window.cairo_create() cr.set_source_surface(sf) cr.paint() cr.set_source_rgba(0,0,0,1) cr.rectangle(x,0,240,400) cr.stroke() cx.set_text(str(x)) im1=Image.open(img) a,b,c,d=im1.getbbox() x=(400*c)/d y=400 im2=im1.resize((x,y),Image.ANTIALIAS) name=img.split("/")[-1] im2.save(tmp+name+"scaled.png") w=gtk.Window() w.set_size_request(x,y+30) w.set_resizable(False) w.set_title("Ritaglio Immagine..") vb=gtk.VBox() w.add(vb) im=gtk.DrawingArea() im.set_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.BUTTON1_MOTION_MASK) vb.add(im) im.connect("motion-notify-event", lambda *w: move_rectangle()) im.connect("expose-event", lambda *w: move_rectangle()) butt=gtk.Button("Ok") butt.set_size_request(80,30) vb.add(butt) vb.set_child_packing(butt,expand=False,fill=False, padding=0,pack_type=gtk.PACK_END) butt.connect("clicked",lambda *w: progress()) w.show_all() sf=ImageSurface.create_from_png(tmp+name+"scaled.png")
def paint_image(self, img, x, y, w, h): #roundtrip via png (yuk) from io import BytesIO png = BytesIO() img.save(png, format="PNG") reader = BytesIO(png.getvalue()) png.close() img = ImageSurface.create_from_png(reader) gc = Context(self.backing) gc.rectangle(x, y, w, h) gc.clip() gc.set_operator(OPERATOR_CLEAR) gc.rectangle(x, y, w, h) gc.fill() gc.set_operator(OPERATOR_SOURCE) gc.translate(x, y) gc.rectangle(0, 0, w, h) gc.set_source_surface(img, x, y) gc.paint()
def get_qrcode_image(print_href): """ Render a QR code to an ImageSurface. """ scheme, host, path, p, query, f = urlparse(print_href) print_path = scheme + '://' + host + path print_id = parse_qs(query).get('id', [''])[0] q = {'print': print_id} u = urljoin(print_path, 'code.php') + '?' + urlencode(q) handle, filename = mkstemp(suffix='.png') try: write(handle, urlopen(u).read()) close(handle) img = ImageSurface.create_from_png(filename) finally: unlink(filename) return img
def get_qrcode_image(print_href): """ Render a QR code to an ImageSurface. """ scheme, host, path, p, query, f = urlparse(print_href) print_path = scheme + "://" + host + path print_id = parse_qs(query).get("id", [""])[0] q = {"print": print_id} u = urljoin(print_path, "code.php") + "?" + urlencode(q) handle, filename = mkstemp(suffix=".png") try: write(handle, urlopen(u).read()) close(handle) img = ImageSurface.create_from_png(filename) finally: unlink(filename) return img
def get_map_image(bbox, width, height, marker, target_dpi=150): """ Get a cairo ImageSurface for a given bounding box, plus the (x, y) point of a marker. Try to match a target DPI. Width and height are given in millimeters! """ template = 'http://a.tile.cloudmade.com/1a914755a77758e49e19a26e799268b7/22677/256/{Z}/{X}/{Y}.png' provider = TemplatedMercatorProvider(template) locA, locB = Location(bbox[0], bbox[1]), Location(bbox[2], bbox[3]) aspect = float(width) / float(height) mmaps = [mapByExtentZoomAspect(provider, locA, locB, zoom, aspect) for zoom in range(10, 19)] inches_wide = width * ptpmm * inppt resolutions = [(mmap.dimensions.x / inches_wide, mmap) for mmap in mmaps] differences = [(abs(dpi - target_dpi), mmap) for (dpi, mmap) in resolutions] diff, mmap = sorted(differences)[0] if (mmap.dimensions.x * mmap.dimensions.y) > (4000 * 4000): raise ValueError('Requested map is too large: %d x %d' % (mmap.dimensions.x, mmap.dimensions.y)) image_path = get_map_cache_path(mmap) if not exists(image_path): print 'no', image_path mmap.draw().save(image_path) img = ImageSurface.create_from_png(image_path) point = mmap.locationPoint(marker) x = width * point.x / mmap.dimensions.x y = height * point.y / mmap.dimensions.y return img, (x, y)
def plugmap(w, s, e, n): west = open_df.long.min() south = open_df.lat.min() east = open_df.long.max() north = open_df.lat.max() zoom = 5 # tiles = list(mercantile.tiles(west, south, east, north, zoom)) print(tiles) tile_size = (256, 256) # создаем пустое изображение в которое как мозайку будем вставлять тайлы # для начала просто попробуем отобразить все четыре тайла в строчку map_image = ImageSurface(FORMAT_ARGB32, tile_size[0] * len(tiles), tile_size[1]) # создаем контекст для рисования ctx = Context(map_image) for idx, t in enumerate(tiles): server = random.choice(['a', 'b', 'c' ]) # у OSM три сервера, распределяем нагрузку url = 'http://{server}.tile.openstreetmap.org/{zoom}/{x}/{y}.png'.format( server=server, zoom=t.z, x=t.x, y=t.y) # запрашиваем изображение response = urllib.request.urlopen(url) # создаем cairo изображние img = ImageSurface.create_from_png(io.BytesIO(response.read())) # рисуем изображение, с правильным сдвигом по оси x ctx.set_source_surface(img, idx * tile_size[0], 0) ctx.paint() # сохраняем собраное изображение в файл with open("map.png", "wb") as f: map_image.write_to_png(f)
def add_print_page(ctx, mmap, href, well_bounds_pt, points_FG, hm2pt_ratio, layout, text, mark, fuzzy, indexees): """ """ print 'Adding print page:', href well_xmin_pt, well_ymin_pt, well_xmax_pt, well_ymax_pt = well_bounds_pt well_width_pt, well_height_pt = well_xmax_pt - well_xmin_pt, well_ymax_pt - well_ymin_pt well_aspect_ratio = well_width_pt / well_height_pt # # Offset drawing area to top-left of map area # ctx.translate(well_xmin_pt, well_ymin_pt) # # Build up map area # img = get_mmap_image(mmap) if layout == 'half-page' and well_aspect_ratio > 1: map_width_pt, map_height_pt = well_width_pt/2, well_height_pt add_page_text(ctx, text, map_width_pt + 24, 24, map_width_pt - 48, map_height_pt - 48) elif layout == 'half-page' and well_aspect_ratio < 1: map_width_pt, map_height_pt = well_width_pt, well_height_pt/2 add_page_text(ctx, text, 32, map_height_pt + 16, map_width_pt - 64, map_height_pt - 32) else: map_width_pt, map_height_pt = well_width_pt, well_height_pt place_image(ctx, img, 0, 0, map_width_pt, map_height_pt) # # Draw a dot if need be # if fuzzy is not None: loc = Location(fuzzy[1], fuzzy[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_circle(ctx, x, y, 20) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(2) ctx.set_dash([2, 6]) ctx.stroke() # # X marks the spot, if needed # if mark is not None: loc = Location(mark[1], mark[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_cross(ctx, x, y, 8, 6) ctx.set_source_rgb(1, 1, 1) ctx.fill() draw_cross(ctx, x, y, 8, 4) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Perhaps some boxes? # page_numbers = [] for page in indexees: north, west, south, east = page['bounds'] ul = mmap.locationPoint(Location(north, west)) lr = mmap.locationPoint(Location(south, east)) x1 = map_width_pt * float(ul.x) / mmap.dimensions.x x2 = map_width_pt * float(lr.x) / mmap.dimensions.x y1 = map_height_pt * float(ul.y) / mmap.dimensions.y y2 = map_height_pt * float(lr.y) / mmap.dimensions.y draw_box(ctx, x1, y1, x2-x1, y2-y1) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(1) ctx.set_dash([]) ctx.stroke() page_numbers.append((x1, y1, x2, y2, page['number'])) # # Calculate positions of registration points # ctx.save() ctx.translate(well_width_pt, well_height_pt) ctx.scale(1/hm2pt_ratio, 1/hm2pt_ratio) reg_points = (point_A, point_B, point_C, point_D, point_E) + points_FG device_points = [ctx.user_to_device(pt.x, pt.y) for pt in reg_points] ctx.restore() # # Draw QR code area # ctx.save() ctx.translate(well_width_pt, well_height_pt) draw_box(ctx, 0, 0, -90, -90) ctx.set_source_rgb(1, 1, 1) ctx.fill() place_image(ctx, get_qrcode_image(href), -83, -83, 83, 83) ctx.restore() # # Draw registration points # for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(.5) ctx.set_dash([1.5, 3]) ctx.stroke() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(1, 1, 1) ctx.fill() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .06 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Draw top-left icon # icon = pathjoin(dirname(__file__), 'images/logo.png') img = ImageSurface.create_from_png(icon) place_image(ctx, img, 0, -36, 129.1, 36) try: font_file = realpath('fonts/LiberationSans-Regular.ttf') if font_file not in cached_fonts: cached_fonts[font_file] = create_cairo_font_face_for_file(font_file) font = cached_fonts[font_file] except: # no text for us. pass else: ctx.set_font_face(font) ctx.set_font_size(12) line = href text_width = ctx.text_extents(line)[2] ctx.move_to(well_width_pt - text_width, -6) ctx.show_text(line) add_scale_bar(ctx, mmap, map_height_pt) ctx.set_font_face(font) ctx.set_font_size(18) for (x1, y1, x2, y2, number) in page_numbers: number_w, number_h = ctx.text_extents(number)[2:4] offset_x, offset_y = (x1 + x2 - number_w) / 2, (y1 + y2 + number_h) / 2 draw_box(ctx, offset_x - 4, offset_y - number_h - 4, number_w + 8, number_h + 8) ctx.set_source_rgb(1, 1, 1) ctx.fill() ctx.set_source_rgb(0, 0, 0) ctx.move_to(offset_x, offset_y) ctx.show_text(number) ctx.show_page()
def add_print_page(ctx, mmap, href, well_bounds_pt, points_FG, hm2pt_ratio): """ """ print 'Adding print page:', href well_xmin_pt, well_ymin_pt, well_xmax_pt, well_ymax_pt = well_bounds_pt well_width_pt, well_height_pt = well_xmax_pt - well_xmin_pt, well_ymax_pt - well_ymin_pt # # Offset drawing area to top-left of map area # ctx.translate(well_xmin_pt, well_ymin_pt) # # Build up map area # draw_box(ctx, 0, 0, well_width_pt, well_height_pt) ctx.set_source_rgb(.9, .9, .9) ctx.fill() img = get_mmap_image(mmap) place_image(ctx, img, 0, 0, well_width_pt, well_height_pt) # # Calculate positions of registration points # ctx.save() ctx.translate(well_width_pt, well_height_pt) ctx.scale(1/hm2pt_ratio, 1/hm2pt_ratio) reg_points = (point_A, point_B, point_C, point_D, point_E) + points_FG device_points = [ctx.user_to_device(pt.x, pt.y) for pt in reg_points] ctx.restore() # # Draw QR code area # ctx.save() ctx.translate(well_width_pt, well_height_pt) draw_box(ctx, 0, 0, -90, -90) ctx.set_source_rgb(1, 1, 1) ctx.fill() place_image(ctx, get_qrcode_image(href), -83, -83, 83, 83) ctx.restore() # # Draw registration points # for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(.5) ctx.set_dash([1.5, 3]) ctx.stroke() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .12 * ptpin) ctx.set_source_rgb(1, 1, 1) ctx.fill() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, .06 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Draw top-left icon # icon = pathjoin(dirname(__file__), '../site/lib/print/icon.png') img = ImageSurface.create_from_png(icon) place_image(ctx, img, 0, -29.13, 19.2, 25.6) try: font = create_cairo_font_face_for_file('fonts/LiberationSans-Bold.ttf') except: # no text for us. pass else: # draw some text. ctx.set_font_face(font) ctx.set_font_size(24) ctx.move_to(0 + 19.2 + 8, -29.13 + 25.6 - 1) ctx.show_text('Walking Papers') try: font = create_cairo_font_face_for_file('fonts/LiberationSans-Regular.ttf') except: # no text for us. pass else: ctx.set_font_face(font) ctx.set_font_size(8) lines = ['OSM data ©2011 CC-BY-SA Openstreetmap.org contributors.', 'Help improve OpenStreetMap by drawing on this map, then visit', href or ''] text_width = max([ctx.text_extents(line)[2] for line in lines]) ctx.move_to(well_width_pt - text_width, -25) ctx.show_text(lines[0]) ctx.move_to(well_width_pt - text_width, -15) ctx.show_text(lines[1]) ctx.move_to(well_width_pt - text_width, -5) ctx.show_text(lines[2]) ctx.show_page()
def generateOverlay(text, font, showFlumotion, showCC, showXiph, width, height): """Generate an transparent image with text + logotypes rendered on top of it suitable for mixing into a video stream @param text: text to put in the top left corner @type text: str @param font: font description used to render the text @type: str @param showFlumotion: if we should show the flumotion logo @type showFlumotion: bool @param showCC: if we should show the Creative Common logo @type showCC: bool @param showXiph: if we should show the xiph logo @type showXiph: bool @param width: width of the image to generate @type width: int @param height: height of the image to generate @type height: int @returns: raw image and if images or if text overflowed @rtype: 3 sized tuple of string and 2 booleans """ from cairo import ImageSurface from cairo import Context image = ImageSurface(cairo.FORMAT_ARGB32, width, height) context = Context(image) subImages = [] if showXiph: subImages.append(os.path.join(configure.imagedir, '36x36', 'xiph.png')) if showCC: subImages.append(os.path.join(configure.imagedir, '36x36', 'cc.png')) if showFlumotion: subImages.append( os.path.join(configure.imagedir, '36x36', 'fluendo.png')) imagesOverflowed = False offsetX = BORDER for subPath in subImages: sub = ImageSurface.create_from_png(subPath) subX = sub.get_width() subY = sub.get_height() offsetY = height - subY - BORDER context.set_source_surface(sub, offsetX, offsetY) context.paint() if (offsetX + subX) > width: imagesOverflowed = True offsetX += subX + BORDER textOverflowed = False if text: pcContext = pangocairo.CairoContext(context) pangoLayout = pcContext.create_layout() if font is not None: font = pango.FontDescription(font) if not font.get_family() or \ not font.get_family().lower() in [family.get_name().lower() for family in pangoLayout.get_context().list_families()]: font.set_family(FONT) if font.get_size() == 0: font.set_size(FONT_SIZE) else: font = pango.FontDescription('%s %s' % (FONT, FONT_PROPS)) pangoLayout.set_font_description(font) context.move_to(TEXT_XOFFSET + 2, TEXT_YOFFSET + 2) pangoLayout.set_markup('<span foreground="black" >%s</span>' % text) pcContext.show_layout(pangoLayout) context.move_to(TEXT_XOFFSET, TEXT_YOFFSET) pangoLayout.set_markup('<span foreground="white" >%s</span>' % text) pcContext.show_layout(pangoLayout) textWidth, textHeight = pangoLayout.get_pixel_size() if textWidth > width: textOverflowed = True if cairo.version < '1.2.6': buf = image.get_data_as_rgba() else: buf = image.get_data() return buf, imagesOverflowed, textOverflowed
def downloadOSMMap(west, south, east, north, zoom, mapType=None): """ Download OSM map of selected area. Original was found on https://smyt.ru/blog/statc-osm-map-with-python/ Map may be download from few different OSM tile servers with different zoom. Download speed depends on size of selected area. Parameters ---------- weast,south,east,north : float coordinates of borders of map zoom : int map zoom, changes map detail mapType : {'white', 'dark', 'toner', None}, optional type of OSM tile server, default is None None - regular OSM map white, dark - white or dark cartodb OSM map toner - stamen toner OSM map Returns ------- numpy.array background map of selected area """ tiles = list(mercantile.tiles(west, south, east, north, zoom)) min_x = min([t.x for t in tiles]) min_y = min([t.y for t in tiles]) max_x = max([t.x for t in tiles]) max_y = max([t.y for t in tiles]) tile_size = (256, 256) map_image = ImageSurface( FORMAT_ARGB32, tile_size[0] * (max_x - min_x + 1), tile_size[1] * (max_y - min_y + 1), ) ctx = Context(map_image) def getTileUrl(mapType, zoom, x, y): if mapType == None: server = random.choice(["a", "b", "c"]) return "http://{server}.tile.openstreetmap.org/{zoom}/{x}/{y}.png".format( server=server, zoom=zoom, x=x, y=y) if mapType == "white": return "http://cartodb-basemaps-1.global.ssl.fastly.net/light_all/{zoom}/{x}/{y}.png".format( zoom=zoom, x=x, y=y) if mapType == "dark": return "http://cartodb-basemaps-2.global.ssl.fastly.net/dark_all/{zoom}/{x}/{y}.png".format( zoom=zoom, x=x, y=y) if mapType == "toner": return "http://a.tile.stamen.com/toner/{zoom}/{x}/{y}.png".format( zoom=zoom, x=x, y=y) for t in tiles: headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3" } url = getTileUrl(mapType, t.z, t.x, t.y) req = Request(url, headers=headers) response = urlopen(req) img = ImageSurface.create_from_png(io.BytesIO(response.read())) ctx.set_source_surface(img, (t.x - min_x) * tile_size[0], (t.y - min_y) * tile_size[0]) ctx.paint() bounds = { "left": min([mercantile.xy_bounds(t).left for t in tiles]), "right": max([mercantile.xy_bounds(t).right for t in tiles]), "bottom": min([mercantile.xy_bounds(t).bottom for t in tiles]), "top": max([mercantile.xy_bounds(t).top for t in tiles]), } kx = map_image.get_width() / (bounds["right"] - bounds["left"]) ky = map_image.get_height() / (bounds["top"] - bounds["bottom"]) left_top = mercantile.xy(west, north) right_bottom = mercantile.xy(east, south) offset_left = (left_top[0] - bounds["left"]) * kx offset_top = (bounds["top"] - left_top[1]) * ky offset_right = (bounds["right"] - right_bottom[0]) * kx offset_bottom = (right_bottom[1] - bounds["bottom"]) * ky result_width = map_image.get_width() - int(offset_left + offset_right) result_height = map_image.get_height() - int(offset_top + offset_bottom) map_image_clipped = ImageSurface(FORMAT_ARGB32, result_width, result_height) ctx = Context(map_image_clipped) ctx.set_source_surface(map_image, -offset_left, -offset_top) ctx.paint() def surface_to_npim(surface): """ Transforms a Cairo surface into a numpy array. """ im = +np.frombuffer(surface.get_data(), np.uint8) H, W = surface.get_height(), surface.get_width() im.shape = (H, W, 4) # for RGBA return im[:, :, :3] return surface_to_npim(map_image_clipped)
image = Image.open(image_row['full_img']) except Exception, e: logging.error("failed to open %s because '%s'" % (image_row['full_img'], e)) logging.info("returning a blank image for %s" % image_row['full_img']) image = Image.new('RGBA', (500, 375)) width, height = image.size aspect = float(width) / float(height) handle, png_path = mkstemp(dir='.', suffix='.png') image.save(png_path) try: image = ImageSurface.create_from_png(png_path) except Exception, e: logging.error("failed to create image surface for %s because '%s'" % (image_row['full_img'], e)) image = Image.new('RGBA', (500, 375)) width, height = image.size aspect = float(width) / float(height) handle, png_path = mkstemp(dir='.', suffix='.png') image.save(png_path) image = ImageSurface.create_from_png(png_path) remove(png_path) close(handle)
def ant_image(self): return ImageSurface.create_from_png('/home/rnetuka/Projekty/Python/Artificial Ant/res/ant.png')
def generateOverlay(text, font, showFlumotion, showCC, showXiph, width, height): """Generate an transparent image with text + logotypes rendered on top of it suitable for mixing into a video stream @param text: text to put in the top left corner @type text: str @param font: font description used to render the text @type: str @param showFlumotion: if we should show the flumotion logo @type showFlumotion: bool @param showCC: if we should show the Creative Common logo @type showCC: bool @param showXiph: if we should show the xiph logo @type showXiph: bool @param width: width of the image to generate @type width: int @param height: height of the image to generate @type height: int @returns: raw image and if images or if text overflowed @rtype: 3 sized tuple of string and 2 booleans """ from cairo import ImageSurface from cairo import Context image = ImageSurface(cairo.FORMAT_ARGB32, width, height) context = Context(image) subImages = [] if showXiph: subImages.append(os.path.join(configure.imagedir, '36x36', 'xiph.png')) if showCC: subImages.append(os.path.join(configure.imagedir, '36x36', 'cc.png')) if showFlumotion: subImages.append(os.path.join(configure.imagedir, '36x36', 'fluendo.png')) imagesOverflowed = False offsetX = BORDER for subPath in subImages: sub = ImageSurface.create_from_png(subPath) subX = sub.get_width() subY = sub.get_height() offsetY = height - subY - BORDER context.set_source_surface(sub, offsetX, offsetY) context.paint() if (offsetX + subX) > width: imagesOverflowed = True offsetX += subX + BORDER textOverflowed = False if text: pcContext = pangocairo.CairoContext(context) pangoLayout = pcContext.create_layout() if font is not None: font = pango.FontDescription(font) if not font.get_family() or \ not font.get_family().lower() in [family.get_name().lower() for family in pangoLayout.get_context().list_families()]: font.set_family(FONT) if font.get_size() == 0: font.set_size(FONT_SIZE) else: font = pango.FontDescription('%s %s' % (FONT, FONT_PROPS)) pangoLayout.set_font_description(font) context.move_to(TEXT_XOFFSET+2, TEXT_YOFFSET+2) pangoLayout.set_markup('<span foreground="black" >%s</span>' % text) pcContext.show_layout(pangoLayout) context.move_to(TEXT_XOFFSET, TEXT_YOFFSET) pangoLayout.set_markup('<span foreground="white" >%s</span>' % text) pcContext.show_layout(pangoLayout) textWidth, textHeight = pangoLayout.get_pixel_size() if textWidth > width: textOverflowed = True if cairo.version < '1.2.6': buf = image.get_data_as_rgba() else: buf = image.get_data() return buf, imagesOverflowed, textOverflowed
def add_print_page(ctx, mmap, href, well_bounds_pt, points_FG, hm2pt_ratio, layout, text, mark, fuzzy, indexees): """ """ print "Adding print page:", href well_xmin_pt, well_ymin_pt, well_xmax_pt, well_ymax_pt = well_bounds_pt well_width_pt, well_height_pt = well_xmax_pt - well_xmin_pt, well_ymax_pt - well_ymin_pt well_aspect_ratio = well_width_pt / well_height_pt # # Offset drawing area to top-left of map area # ctx.translate(well_xmin_pt, well_ymin_pt) # # Build up map area # img = get_mmap_image(mmap) if layout == "half-page" and well_aspect_ratio > 1: map_width_pt, map_height_pt = well_width_pt / 2, well_height_pt add_page_text(ctx, text, map_width_pt + 24, 24, map_width_pt - 48, map_height_pt - 48) elif layout == "half-page" and well_aspect_ratio < 1: map_width_pt, map_height_pt = well_width_pt, well_height_pt / 2 add_page_text(ctx, text, 32, map_height_pt + 16, map_width_pt - 64, map_height_pt - 32) else: map_width_pt, map_height_pt = well_width_pt, well_height_pt place_image(ctx, img, 0, 0, map_width_pt, map_height_pt) # # Draw a dot if need be # if fuzzy is not None: loc = Location(fuzzy[1], fuzzy[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_circle(ctx, x, y, 20) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(2) ctx.set_dash([2, 6]) ctx.stroke() # # X marks the spot, if needed # if mark is not None: loc = Location(mark[1], mark[0]) pt = mmap.locationPoint(loc) x = map_width_pt * float(pt.x) / mmap.dimensions.x y = map_height_pt * float(pt.y) / mmap.dimensions.y draw_cross(ctx, x, y, 8, 6) ctx.set_source_rgb(1, 1, 1) ctx.fill() draw_cross(ctx, x, y, 8, 4) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Perhaps some boxes? # page_numbers = [] for page in indexees: north, west, south, east = page["bounds"] ul = mmap.locationPoint(Location(north, west)) lr = mmap.locationPoint(Location(south, east)) x1 = map_width_pt * float(ul.x) / mmap.dimensions.x x2 = map_width_pt * float(lr.x) / mmap.dimensions.x y1 = map_height_pt * float(ul.y) / mmap.dimensions.y y2 = map_height_pt * float(lr.y) / mmap.dimensions.y draw_box(ctx, x1, y1, x2 - x1, y2 - y1) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(1) ctx.set_dash([]) ctx.stroke() page_numbers.append((x1, y1, x2, y2, page["number"])) # # Calculate positions of registration points # ctx.save() ctx.translate(well_width_pt, well_height_pt) ctx.scale(1 / hm2pt_ratio, 1 / hm2pt_ratio) reg_points = (point_A, point_B, point_C, point_D, point_E) + points_FG device_points = [ctx.user_to_device(pt.x, pt.y) for pt in reg_points] ctx.restore() # # Draw QR code area # ctx.save() ctx.translate(well_width_pt, well_height_pt) draw_box(ctx, 0, 0, -90, -90) ctx.set_source_rgb(1, 1, 1) ctx.fill() place_image(ctx, get_qrcode_image(href), -83, -83, 83, 83) ctx.restore() # # Draw registration points # for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, 0.12 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.set_line_width(0.5) ctx.set_dash([1.5, 3]) ctx.stroke() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, 0.12 * ptpin) ctx.set_source_rgb(1, 1, 1) ctx.fill() for (x, y) in device_points: x, y = ctx.device_to_user(x, y) draw_circle(ctx, x, y, 0.06 * ptpin) ctx.set_source_rgb(0, 0, 0) ctx.fill() # # Draw top-left icon # icon = pathjoin(dirname(__file__), "images/logo.png") img = ImageSurface.create_from_png(icon) place_image(ctx, img, 0, -36, 129.1, 36) try: font_file = realpath("fonts/Helvetica.ttf") if font_file not in cached_fonts: cached_fonts[font_file] = create_cairo_font_face_for_file(font_file) font = cached_fonts[font_file] except: # no text for us. pass else: ctx.set_font_face(font) ctx.set_font_size(12) line = href text_width = ctx.text_extents(line)[2] ctx.move_to(well_width_pt - text_width, -6) ctx.show_text(line) add_scale_bar(ctx, mmap, map_height_pt) ctx.set_font_face(font) ctx.set_font_size(18) for (x1, y1, x2, y2, number) in page_numbers: number_w, number_h = ctx.text_extents(number)[2:4] offset_x, offset_y = (x1 + x2 - number_w) / 2, (y1 + y2 + number_h) / 2 draw_box(ctx, offset_x - 4, offset_y - number_h - 4, number_w + 8, number_h + 8) ctx.set_source_rgb(1, 1, 1) ctx.fill() ctx.set_source_rgb(0, 0, 0) ctx.move_to(offset_x, offset_y) ctx.show_text(number) ctx.show_page()