Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_image_bytearray_buffer():
if '__pypy__' in sys.modules:
pytest.xfail()
# Also test buffers through ctypes.c_char.from_buffer,
# not available on PyPy
data = bytearray(800)
surface = ImageSurface.create_for_data(data, cairocffi.FORMAT_ARGB32,
10, 20, stride=40)
Context(surface).paint_with_alpha(0.5)
assert data == pixel(b'\x80\x00\x00\x00') * 200
def _init_state():
global surface
surface = cairo.RecordingSurface(cairo.CONTENT_COLOR_ALPHA, None)
_state["ctx"] = cairo.Context(surface)
_state["color"] = (0, 0, 0, 1)
_state["depth"] = 0
_state["cnt_elements"] = 0
def __init__(self, context, font_size, style):
self.context = context
hinting = context.enable_hinting if context else False
cairo_dummy_context = (
cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1))
if hinting else cairo.Context(cairo.PDFSurface(None, 1, 1)))
self.layout = ffi.gc(
pangocairo.pango_cairo_create_layout(ffi.cast(
'cairo_t *', cairo_dummy_context._pointer)),
gobject.g_object_unref)
pango_context = pango.pango_layout_get_context(self.layout)
if context and context.font_config.font_map:
pango.pango_context_set_font_map(
pango_context, context.font_config.font_map)
self.font = ffi.gc(
pango.pango_font_description_new(),
pango.pango_font_description_free)
if style['font_language_override'] != 'normal':
lang_p, lang = unicode_to_char_p(LST_TO_ISO.get(
style['font_language_override'].lower(),
style['font_language_override']))
elif style['lang']:
num_bins_y = int(math.ceil((yh-yl)/bin_size_y))
x = np.array(pos[:num_nodes])
y = np.array(pos[num_nodes:])
node_size_x = np.array(node_size_x)
node_size_y = np.array(node_size_y)
pin_offset_x = np.array(pin_offset_x)
pin_offset_y = np.array(pin_offset_y)
pin2node_map = np.array(pin2node_map)
try:
tt = time.time()
width = 800
height = 800
line_width = 0.1
padding = 0
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(surface)
# Do not use scale function.
# This is not compatible with show_text
if num_movable_nodes < num_physical_nodes:
layout_xl = min(np.amin(x[num_movable_nodes:num_physical_nodes]), xl)
layout_yl = min(np.amin(y[num_movable_nodes:num_physical_nodes]), yl)
layout_xh = max(np.amax(x[num_movable_nodes:num_physical_nodes]+node_size_x[num_movable_nodes:num_physical_nodes]), xh)
layout_yh = max(np.amax(y[num_movable_nodes:num_physical_nodes]+node_size_y[num_movable_nodes:num_physical_nodes]), yh)
else:
layout_xl = xl
layout_yl = yl
layout_xh = xh
layout_yh = yh
def bin_xl(id_x):
"""
def render_with_cairo(az, imgsize, extent, filename):
"""
Draw current tiling of `az` (possibly have holes)
to a png image with cairo.
Parameters
----------
:az: an instance of the AztecDiamond class.
:imgsize: image size in pixels, e.g. size = 600 means 600x600.
:extent: range of the axis: [-extent, extent] x [-extent, extent]
:filename: output filename, must be a .png image.
"""
import cairocffi as cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, imgsize, imgsize)
surface.set_fallback_resolution(100, 100)
ctx = cairo.Context(surface)
ctx.scale(imgsize / (2.0 * extent), -imgsize / (2.0 * extent))
ctx.translate(extent, -extent)
ctx.set_source_rgb(1, 1, 1)
ctx.paint()
margin = 0.1
for (i, j) in az.cells:
if (az.is_black(i, j) and az.tile[(i, j)] is not None):
if az.tile[(i, j)] == 'n':
ctx.rectangle(i - 1 + margin, j + margin,
2 - 2 * margin, 1 - 2 * margin)
ctx.set_source_rgb(*N_COLOR)
if az.tile[(i, j)] == 's':
def fade_background_to_image(path, secs, fps):
# Assume the painting takes 0 seconds for this calculation. In reality
# this is a crappy assumption, but we're just fading in a wallpaper so
# who cares.
steps = max(1, fps * secs)
step = 1 / steps
sleep = secs / steps
image = load_image(path)
wrapper = ConnectionWrapper(xcffib.Connection())
pixmap = wrapper.get_current_background()
surface = wrapper.create_surface_for_pixmap(pixmap)
with cairocffi.Context(surface) as context:
context.set_source_surface(image)
opacity = 0
for i in range(steps):
context.paint_with_alpha(i * step)
wrapper.set_background(pixmap)
time.sleep(sleep)
def paint_text(text, w, h, rotate=False, ud=False, multi_fonts=False):
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)
with cairo.Context(surface) as context:
context.set_source_rgb(1, 1, 1) # White
context.paint()
# this font list works in CentOS 7
if multi_fonts:
fonts = ['Century Schoolbook', 'Courier', 'STIX', 'URW Chancery L', 'FreeMono']
context.select_font_face(np.random.choice(fonts), cairo.FONT_SLANT_NORMAL,
np.random.choice([cairo.FONT_WEIGHT_BOLD, cairo.FONT_WEIGHT_NORMAL]))
else:
context.select_font_face('Courier', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
context.set_font_size(25)
box = context.text_extents(text)
border_w_h = (4, 4)
if box[2] > (w - 2 * border_w_h[1]) or box[3] > (h - 2 * border_w_h[0]):
raise IOError('Could not fit string into image. Max char count is too large for given image width.')
# teach the RNN translational invariance by
def _generate_layer(self, transcription, page, layer):
surface = PDFSurface(layer, *page.page_size)
context = Context(surface)
# context.select_font_face('Georgia')
context.set_source_rgba(1, 1, 1, 1/256) # almost invisible
context.set_font_size(2)
for line_ink, line_transcription in zip(page.lines, transcription):
ink, transformation = writing.normalized(line_ink)
context.save()
context.transform(Matrix(*(Transformation.translation(0, page.page_size[1]).parameter)))
context.transform(Matrix(*(Transformation.mirror(0).parameter)))
context.transform(Matrix(*((~transformation).parameter)))
context.transform(Matrix(*(Transformation.mirror(0).parameter)))
HANDWRITING_WIDTH = ink.boundary_box[1]
TYPEWRITING_WIDTH = context.text_extents(line_transcription)[2]
context.scale(HANDWRITING_WIDTH/TYPEWRITING_WIDTH, 1)
context.move_to(0, 0)
context.show_text(line_transcription)
context.restore()
base[:,:,channel] = (base[:,:,channel] * base_alpha + \
overlay[:,:,channel] * overlay_alpha * \
(1 - base_alpha)) / \
(base_alpha + overlay_alpha * (1 - base_alpha))
cv2.imwrite(outp_name, base)
###########################################################################
# Code below here is for drawing vector layers within the PDF #
# Leaving it in just because it was a pain to come up with the first time #
###########################################################################
if shape_overlays or point_overlays:
im = cairo.ImageSurface.create_from_png(outp_name)
ctx = cairo.Context(im)
if shape_overlays:
for shape_overlay in shape_overlays:
if shape_overlay:
shape_overlay = json.loads(shape_overlay)
if shape_overlay.get('geometry'):
shape_overlay = shape_overlay['geometry']
color = hex_to_rgb('#f06eaa')
coords = shape_overlay['coordinates'][0]
x, y = get_pixel_coords(coords[0], grid['zoom'], bmin_rx, bmin_ry)
ctx.move_to(x,y)
ctx.set_line_width(4.0)
red, green, blue = [float(c) for c in color]
ctx.set_source_rgba(red/255, green/255, blue/255, 0.3)
for p in coords[1:]:
x, y = get_pixel_coords(p, grid['zoom'], bmin_rx, bmin_ry)
self.stroke_and_fill = True
width, height, viewbox = node_format(self, tree)
if viewbox is None:
viewbox = (0, 0, width, height)
if output_width and output_height:
width, height = output_width, output_height
else:
width *= scale
height *= scale
# Actual surface dimensions: may be rounded on raster surfaces types
self.cairo, self.width, self.height = self._create_surface(
width * self.device_units_per_user_units,
height * self.device_units_per_user_units)
self.context = cairo.Context(self.cairo)
# We must scale the context as the surface size is using physical units
self.context.scale(
self.device_units_per_user_units, self.device_units_per_user_units)
# Initial, non-rounded dimensions
self.set_context_size(width, height, viewbox, tree)
self.context.move_to(0, 0)
if background_color:
self.context.set_source_rgba(*color(background_color))
self.context.paint()
self.map_rgba = map_rgba
self.map_image = map_image
self.draw(tree)