Build an svg image tag.
436775
function(url, img) {
        var svgImage = document.createElementNS(SVG_NS_URL, 'image');
        svgImage.setAttributeNS(XLINK_NS_URL, 'xlink:href', url);
        svgImage.setAttribute('x', 0);
        svgImage.setAttribute('y', 0);
        svgImage.setAttribute('width', img.width);
        svgImage.setAttribute('height', img.height);
        return svgImage;
      }
576558
def svg(*args, **kw):
    
    class svg(type(helper.svg())):
        
        def __init__(self, *args, **kw):
            super(self.__class__, self).__init__(*args, **kw)
            # cartesian grid on/off
            self.__dict__['grid'] = False
            # axes on/off
            self.__dict__['axes'] = False
            # show origin
            self.__dict__['origin'] = False
            # grid aspects
            self.__dict__['grid_aspects'] = (4, 8)
            # x
            self.__dict__['x'] = 200
            # y
            self.__dict__['y'] = 200
            # elements
            self.__dict__['elements'] = []
            # size of the svg canvas, width and height
            self.__dict__['size'] = (100, 100)
            # grid id
            self.__dict__['grid_id'] = "gid%s" % id(self)
            # grid item id
            self.__dict__['grid_item_id'] = "gitem%s" % id(self)
            # grid width
            width = kw['width'] if kw.has_key('width') else self.__dict__['x']*2
            # grid height
            height = kw['height'] if kw.has_key('height') else self.__dict__['y']*2
            self.set_size(width, height)
        
        def set_grid(self, grid = True):
            self.__dict__['grid'] = grid
            return self
        
        def set_axes(self, axes = True):
            self.__dict__['axes'] = axes
            return self
        
        def set_origin(self, origin = True):
            self.__dict__['origin'] = origin
            return self
        
        def set_size(self, width, height):
            self.__dict__['x'] = width/2
            self.__dict__['y'] = height/2
            self.__dict__['size'] = (width, height)
            self.width = width
            self.height = height
            self.viewbox = "0 0 %s %s" % (width+1, height+1)
            return self
        
        def set_text(self, *args, **kw):
            kw['x'] = self.__dict__['x']+kw['x'] if kw.has_key('x') else self.__dict__['x'] 
            kw['y'] = self.__dict__['y']-kw['y'] if kw.has_key('y') else self.__dict__['y']
            self.__dict__['elements'].append(helper.text(*args, **kw))
            return self
        
        def set_rectangle(self, *args, **kw):
            kw['x'] = self.__dict__['x']+kw['x'] if kw.has_key('x') else self.__dict__['x']
            kw['y'] = self.__dict__['y']-kw['y'] if kw.has_key('y') else self.__dict__['y']
            self.__dict__['elements'].append(helper.rect(*args, **kw))
            return self
        
        def set_group(self, *args, **kw):
            self.__dict__['elements'].append(helper.g(*args, **kw))
            return self
        
        def set_defs(self, *args, **kw):
            self.__dict__['elements'].append(helper.defs(*args, **kw))
            return self
        
        def set_line(self, *args, **kw):
            kw['x1'] = self.__dict__['x']+kw['x1'] if kw.has_key('x1') else self.__dict__['x']
            kw['y1'] = self.__dict__['y']-kw['y1'] if kw.has_key('y1') else self.__dict__['y']
            kw['x2'] = self.__dict__['x']+kw['x2'] if kw.has_key('x2') else self.__dict__['x'] + 10
            kw['y2'] = self.__dict__['y']-kw['y2'] if kw.has_key('y2') else self.__dict__['y'] + 10
            self.__dict__['elements'].append(helper.line(*args, **kw))
            return self
        
        def set_circle(self, *args, **kw):
            kw['cx'] = self.__dict__['x']+kw['cx'] if kw.has_key('cx') else self.__dict__['x']
            kw['cy'] = self.__dict__['y']-kw['cy'] if kw.has_key('cy') else self.__dict__['y']
            self.__dict__['elements'].append(helper.circle(*args, **kw))
            return self
        
        def set_triangle(self, *args, **kw):
            kw['sides'] = 3
            return self.set_regular_polygon(*args, **kw)
        
        def set_square(self, *args, **kw):
            kw['sides'] = 4
            return self.set_regular_polygon(*args, **kw)
        
        def set_pentagon(self, *args, **kw):
            kw['sides'] = 5
            return self.set_regular_polygon(*args, **kw)
        
        def set_hexagon(self, *args, **kw):
            kw['sides'] = 6
            return self.set_regular_polygon(*args, **kw)
        
        def set_regular_polygon(self, *args, **kw):
            # set default properties for vertex
            kw['cx'] = kw['cx']+self.__dict__['x'] if kw.has_key('cx') else self.__dict__['x']
            kw['cy'] = kw['cy']-self.__dict__['y'] if kw.has_key('cy') else self.__dict__['y']
            kw['radius'] = kw['radius'] if kw.has_key('radius') else 1
            kw['sides'] = kw['sides'] if kw.has_key('sides') else 4
            kw['degrees'] = kw['degrees'] if kw.has_key('degrees') else 0
            # set generate polygon points
            points = self.polygon_points(self.vertex(cx=kw['cx'],
                                                     cy=kw['cy'],
                                                     radius=kw['radius'],
                                                     sides=kw['sides'],
                                                     degrees=kw['degrees']))
            # delete default properties
            del kw['cx']
            del kw['cy']
            del kw['radius']
            del kw['sides']
            del kw['degrees']
            # create polygon with given points and keywords
            self.__dict__['elements'].append(helper.polygon(points=points, *args, **kw))
            return self
        
        def polygon_points(self, vertex):
            return ' '.join(['%s,%s' % (point[0], point[1]) for point in vertex])
        
        def vertex(self, cx = 0, cy = 0, sides = 4, radius = 1, degrees = 0):
            centerAng = 2*pi/sides
            startAng = pi*degrees/180
            points = []
            for i in range(0, sides):
                ang = startAng + (i*centerAng);
                x = round(cx + radius*cos(ang), 2)
                y = round(cy - radius*sin(ang), 2)
                points.append([x,y])
            return points
        
        def _set_grid(self):
            """ Set up background grid for drawing canvas """
            grid_sizex = self.__dict__['size'][0]/self.__dict__['grid_aspects'][0]
            grid_sizey = self.__dict__['size'][1]/self.__dict__['grid_aspects'][0]
            
            sizex = grid_sizex*(1.0/self.__dict__['grid_aspects'][1])
            sizey = grid_sizey*(1.0/self.__dict__['grid_aspects'][1])
            
            defs = helper.defs()
            defs += helper.pattern(helper.path(**{'d': 'M %s 0 L 0 0 0 %s' % (sizex, sizey), 'fill': 'none', 'stroke': 'gray', 'stroke-width': 0.5}),
                                   **{'id': self.__dict__['grid_item_id'], 'width': sizex, 'height': sizey, 'patternUnits': 'userSpaceOnUse'})
            defs += helper.pattern(helper.path(**{'d': 'M %s 0 L 0 0 0 %s' % (grid_sizex, grid_sizey), 'fill': 'none', 'stroke': 'gray', 'stroke-width': 1}),
                                   helper.rect(width=grid_sizex, height=grid_sizey, fill="url(#%s)" % self.__dict__['grid_item_id']),
                                   **{'id': self.__dict__['grid_id'], 'width': grid_sizex, 'height': grid_sizey, 'patternUnits': 'userSpaceOnUse'})
            self += defs
            self += helper.rect(fill="white", height=self.__dict__['size'][0]+1, width=self.__dict__['size'][1]+1)
            self += helper.rect(fill="url(#%s)" % self.__dict__['grid_id'], height=self.__dict__['size'][0]+1, width=self.__dict__['size'][1]+1)
            
        def _set_axes(self):
            """ Set up x and y axis for drawing canvas """
            self += helper.line(stroke="black", x1=self.__dict__['x'], x2=self.__dict__['x'], y1=0, y2=self.__dict__['y']*2)
            self += helper.line(stroke="black", x1=0, x2=self.__dict__['x']*2, y1=self.__dict__['y'], y2=self.__dict__['y'])
        
        def _set_origin(self):
            """ Set up origin dot and x/y coordinates for drawing canvas """
            self += helper.circle(cx=self.__dict__['x'], cy=self.__dict__['y'], r=2, fill="black", stroke="black", style="fill-opacity: 50%")
            self += helper.text("(0,0)", x=self.__dict__['x']+5, y=self.__dict__['y']-5, style="fill-opacity: 50%")
        
        def __str__(self):
            if self.__dict__['grid']:
                self._set_grid()
            if self.__dict__['axes']:
                self._set_axes()
            if self.__dict__['origin']:
                self._set_origin()
            if self.__dict__['elements']:
                for element in self.__dict__['elements']:
                    self += element
            return super(self.__class__, self).__str__()
    
    return svg(*args, **kw)
266131
private void render(SVG.Image obj)
   {
      debug("Image render");

      if (obj.width == null || obj.width.isZero() ||
          obj.height == null || obj.height.isZero())
         return;

      if (obj.href == null)
         return;

      // "If attribute 'preserveAspectRatio' is not specified, then the effect is as if a value of xMidYMid meet were specified."
      PreserveAspectRatio  positioning = (obj.preserveAspectRatio != null) ? obj.preserveAspectRatio : PreserveAspectRatio.LETTERBOX;

      // Locate the referenced image
      Bitmap  image = checkForImageDataURL(obj.href);
      if (image == null)
      {
         SVGExternalFileResolver  fileResolver = SVG.getFileResolver();
         if (fileResolver == null)
            return;

         image = fileResolver.resolveImage(obj.href);
      }
      if (image == null) {
         error("Could not locate image '%s'", obj.href);
         return;
      }
      SVG.Box  imageNaturalSize = new SVG.Box(0,  0,  image.getWidth(), image.getHeight());

      updateStyleForElement(state, obj);

      if (!display())
         return;
      if (!visible())
         return;

      if (obj.transform != null) {
         canvas.concat(obj.transform);
      }

      float  _x = (obj.x != null) ? obj.x.floatValueX(this) : 0f;
      float  _y = (obj.y != null) ? obj.y.floatValueY(this) : 0f;
      float  _w = obj.width.floatValueX(this);
      float  _h = obj.height.floatValueX(this);
      state.viewPort = new SVG.Box(_x, _y, _w, _h);

      if (!state.style.overflow) {
         setClipRect(state.viewPort.minX, state.viewPort.minY, state.viewPort.width, state.viewPort.height);
      }

      obj.boundingBox = state.viewPort;
      updateParentBoundingBox(obj);

      checkForClipPath(obj);

      boolean  compositing = pushLayer();

      viewportFill();

      canvas.save();

      // Local transform from image's natural dimensions to the specified SVG dimensions
      canvas.concat(calculateViewBoxTransform(state.viewPort, imageNaturalSize, positioning));

      Paint  bmPaint = new Paint((state.style.imageRendering == RenderQuality.optimizeSpeed) ? 0 : Paint.FILTER_BITMAP_FLAG);
      canvas.drawBitmap(image, 0, 0, bmPaint);

      canvas.restore();

      if (compositing)
         popLayer(obj);
   }
974248
function makeElement(name) {
      return name === 'svg' ? document.createElementNS(SVG_NS, name) : document.createElement(name)
    }
980562
private void render(SVG.Svg obj)
   {
      // <svg> elements establish a new viewport.
      Box viewPort = makeViewPort(obj.x, obj.y, obj.width, obj.height);

      render(obj, viewPort, obj.viewBox, obj.preserveAspectRatio);
   }
255399
function offlineImage(name, width, height) {
  return
    `<?xml version="1.0"?>
<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <g fill="none" fill-rule="evenodd"><path fill="#F8BBD0" d="M0 0h${width}v${height}H0z"/></g>
  <text text-anchor="middle" x="${Math.floor(width / 2)}" y="${Math.floor(height / 2)}">image offline (${name})</text>
<style><![CDATA[
text{
  font: 48px Roboto,Verdana, Helvetica, Arial, sans-serif;
}
]]></style>
</svg>`;
}
1114627
function image(url) {
  url = url.replace(/\??#.*$/, '');
  var inliner = this;
  this.emit('progress', 'get image ' + basename(url));
  return this.get(url, { encoding: 'binary' }).then(function then(res) {
    if (url.indexOf('data:') === 0) {
      return url;
    }

    debug('image loaded: %s', url);

    // if the url is SVG, let's compress and use the XML directly
    if (res.body && mime.lookup(url) === 'image/svg+xml' &&
      !inliner.options.nosvg) {
      return new Promise(function (resolve, reject) {
        svgo.optimize(res.body.toString(), function (result) {
          debug('optimising svg');
          if (result.error) {
            debug('errored', result.error);
            return reject(new Error(result.error));
          }
          // supposing/given:
          // - we are in a CSS single quoted string
          // - this css *may* be in a HTML file, in a <style>
          // - this css *may* be in a HTML file, in a double-quoted attribute
          // - the optimizer possibly replaced:
          //   - & by &amp;  <<< unhandled: add a &amp; in the svg text to test
          //   - ' by &apos;
          //   - " by &quot; (not around attributes)
          // Thus, we have to do a tricky escape pattern
          // ... we use % encoding for html level escape
          // ... we need to use proper \ escape for css level escape
          // ... (or we could have a ' in ' problem (nested sinle quotes))
          // ... so, before anything, we need to escape both \ and %
          var replacements = {
            '<': '%3C',  // html escape
            '"': '%22',  // html escape
            '&quot;': '%22',  // html escape
            '#': '%23',  // css url path escape
            '\n': '\\n', // css string escape
            '\'': '\\\'',// css string escape
            '&apos;': '\\\'',// css string escape
          };
          var body = result.data.replace(/\\/g, '\\').replace(/%/g, '%25')
                     .replace(/[<"#\n']|&quot;|&apos;/g, function (m) {
            return replacements[m];
          });
          resolve('data:image/svg+xml;utf8,' + body);
        });
      });
    }

    // otherwise we base64 encode the image
    return 'data:' + res.headers['content-type'] + ';base64,' +
            new Buffer(res.body, 'binary').toString('base64');

  }).catch(function errorHandle(error) {
    debug('image %s failed to load', url, error);
    throw error;
  });
}
1365026
function savePNG(svg, scaleFactor) {
    svg.selectAll(classes.join(', ')).each(function inlineProps() {
        const element = this;
        const computedStyle = getComputedStyle(element, null);

        // loop through and compute inline svg styles
        for (let i = 0; i < computedStyle.length; i += 1) {
            const property = computedStyle.item(i);
            const value = computedStyle.getPropertyValue(property);
            element.style[property] = value;
        }
    });

    saveSvgAsPng(
        svg.node(),
        `${svg
            .select('title')
            .text()
            .replace(/\s/g, '-')
            .toLowerCase()}.png`,
        { scale: scaleFactor },
    );
}
541817
function process (svg, { prefix }) {
  // Inject a <style> in the SVG document to allow changing colors
  svg = svg.replace(/<(path|circle) /gi, (_, tag) => `<${tag} fill="__COLOR__" `)

  // Since this is a data: URI, we want to encode it with %23 and such
  svg = encodeURIComponent(svg)

  // We want the #{...} interpolation to be outside the URI encoding
  svg = svg.replace(/__COLOR__/g, '#{' + prefix + '-fix-color($color)}')

  svg = 'data:image/svg+xml;charset=utf-8,' + svg

  return svg
}
655976
def image_tag(src, options={})
      src = "/images/#{src}" unless src.include? "://" # Add images directory to path if not a full URL
      options[:src] = url_for(src)
      tag(:img, options)
    end
369477
function(width, height) {
									var newImage = svgCanvas.addSvgElementFromJson({
										element: 'image',
										attr: {
											x: 0,
											y: 0,
											width: width,
											height: height,
											id: svgCanvas.getNextId(),
											style: 'pointer-events:inherit'
										}
									});
									svgCanvas.setHref(newImage, e.target.result);
									svgCanvas.selectOnly([newImage]);
									svgCanvas.alignSelectedElements('m', 'page');
									svgCanvas.alignSelectedElements('c', 'page');
									updateContextPanel();
								}
605449
def extract_svg(display_object, dpi=300, compress='auto'):
    
    image_svg = svg2str(display_object, dpi)
    if compress is True or compress == 'auto':
        image_svg = svg_compress(image_svg, compress)
    image_svg = re.sub(' height="[0-9]+[a-z]*"', '', image_svg, count=1)
    image_svg = re.sub(' width="[0-9]+[a-z]*"', '', image_svg, count=1)
    image_svg = re.sub(' viewBox',
                       ' preseveAspectRation="xMidYMid meet" viewBox',
                       image_svg, count=1)
    start_tag = '<svg '
    start_idx = image_svg.find(start_tag)
    end_tag = '</svg>'
    end_idx = image_svg.rfind(end_tag)
    if start_idx is -1 or end_idx is -1:
        NIWORKFLOWS_LOG.info('svg tags not found in extract_svg')
    # rfind gives the start index of the substr. We want this substr
    # included in our return value so we add its length to the index.
    end_idx += len(end_tag)
    return image_svg[start_idx:end_idx]
1277446
function(svg){
      if (!svg){
        throw new Error('.toString: No SVG found.');
      }

      [
        ['version', 1.1],
        ['xmlns', "http://www.w3.org/2000/svg"],
      ].forEach(function(item){
        svg.setAttribute(item[0], item[1]);
      });
      return svg.outerHTML;
    }
1370637
function (tipElement, svg) {
    _element = tipElement;
    _bubble = _element.find('.bubble');
    _svg = svg;
    _svgPoint = svg[0].createSVGPoint();
  }
1201308
def _handle_tag(self, tag, attrs, self_closing):
        

        if tag.lower() == 'img':
            attrs = self._image_attrs(attrs)

        # Remap the attributes
        out_attrs = []
        for key, val in attrs:
            if (key.lower() == 'href'
                    or (key.lower() == 'src' and not tag.lower() == 'img')):
                out_attrs.append((key, links.resolve(
                    val, self._search_path, self._config.get('absolute'))))
            else:
                out_attrs.append((key, val))

        self.append(
            utils.make_tag(
                tag,
                out_attrs,
                self_closing))
1324261
def get_img_tag(self, title='', alt_text='', **kwargs):
        

        try:
            style = []

            for key in ('img_style', 'style'):
                if key in kwargs:
                    if isinstance(kwargs[key], (list, tuple, set)):
                        style += list(kwargs[key])
                    else:
                        style.append(kwargs[key])

            if 'shape' in kwargs:
                shape = self._get_shape_style(**kwargs)
                if shape:
                    style.append("shape-outside: url('{}')".format(shape))

            attrs = {
                'alt': alt_text,
                'title': title,
                **self.get_img_attrs(style, **kwargs)
            }

            return flask.Markup(
                self._wrap_link_target(
                    kwargs,
                    utils.make_tag(
                        'img', attrs, start_end=kwargs.get('xhtml')),
                    title))
        except FileNotFoundError as error:
            text = '<span class="error">Image not found: <code>{}</code>'.format(
                html.escape(error.filename))
            if ' ' in error.filename:
                text += ' (Did you forget a <code>|</code>?)'
            text += '</span>'
            return flask.Markup(text)
355426
def process_draw_image( element, output_node )
      pic_name = element.attribute("#{@xlink_ns}:href").value
      if (@image_dir != nil) then
        img = emit_element( output_node, "img" )
        img.attributes["alt"] = pic_name

        # Get rid of everything before the last / in the filename
        base_name = pic_name;
        if ((pos = base_name.rindex('/')) != nil) then
          base_name = base_name[pos + 1 .. -1]
        end
        copy_image_file( pic_name, @image_dir, base_name )
        img.attributes["src"] = "#{@image_dir}/#{base_name}"
        width = element.parent.attribute("#{@svg_ns}:width")
        height= element.parent.attribute("#{@svg_ns}:height")
        if (width != nil && height != nil) then
          img.attributes["style"] = "width:#{width.value}; " +
            "height:#{height.value}"
        end
      else
        div = emit_element( output_node, "div" )
        div.add_text( pic_name )
      end
    end