Renders images into inline image using base64 encoding
325857
public function renderImages()
    {
        foreach ($this->getVariables() as $key => $variable) {
            if (is_file($variable)) {
                $type = pathinfo($variable, PATHINFO_EXTENSION);
                $data = file_get_contents($variable);
                $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                $this->setVariable($key, $base64);
            }
        }
    }
622177
def _render(template, callable_, args, data, as_unicode=False):
    """"""

    if as_unicode:
        buf = util.FastEncodingBuffer(as_unicode=True)
    elif template.bytestring_passthrough:
        buf = compat.StringIO()
    else:
        buf = util.FastEncodingBuffer(
                        as_unicode=as_unicode,
                        encoding=template.output_encoding,
                        errors=template.encoding_errors)
    context = Context(buf, **data)
    context._outputting_as_unicode = as_unicode
    context._set_with_template(template)

    _render_context(template, callable_, context, *args,
                            **_kwargs_for_callable(callable_, data))
    return context._pop_buffer().getvalue()
1334929
def render
      result = {:text => @generator.to_s, :content_type => Mime::JS}

      # iframed uploads context overloading
      if @template.request.content_type == 'multipart/form-data'
        result[:content_type] = Mime::HTML
        result[:layout]       = nil
        result[:text]         = %Q{
<!-- iframed uploads JS responses layout -->
<html>
  <head>
    <script type="text/javascript">
      with (window.parent) {
        #{result[:text]}
      }
    </script>
  </head>
</html>
        }.strip
      end

      result.merge! @options
    end
46548
def render_image_link_lazy(options = {})
      # options = {
      #     :alt_image,
      #     :image,
      #     :a_href,
      #     :aid,
      #     :a_class,
      #     :target,
      #     :style
      # }

      alt_image = options.fetch(:alt_image, '')
      image = options.fetch(:image, '1px_invisible.gif')
      a_href = options.fetch(:a_href, '/')
      aid = options.fetch(:aid, '')
      a_class = options.fetch(:a_class, '')
      target = options.fetch(:target, '_self')
      a_css_style = options.fetch(:a_css_style, '')
      a_rel = options.fetch(:a_rel, 'follow')

      render :partial => 'c80_lazy_images/image_link_lazy',
             :locals => {
                 :alt_image => alt_image,
                 :image => image,
                 :a_href => a_href,
                 :aid => aid,
                 :a_class => a_class,
                 :target => target,
                 :a_css_style => a_css_style,
                 :a_rel => a_rel
             }
    end
1325164
def renderThumbnail(self, relpath=""):
        """"""
        # no thumbnail -- return empty string
        if self.thumbnail is None:
            return ""
        # else thumbnail is same as full image (because image was small enough), insert directly
        elif self.thumbnail is self.fullimage:
            fname = relpath + self.fullimage
            return """<IMG SRC="%s" ALT="%s"></IMG>""" % (quote_url(fname), quote_url(os.path.basename(self.filename)))
        # else return thumbnail linking to full image
        else:
            tname = relpath + self.thumbnail
            fname = relpath + self.fullimage
            return """<A HREF="%s"><IMG SRC="%s" ALT="%s"></A>""" % (
            quote_url(fname), quote_url(tname), quote_url(os.path.basename(self.filename)))
1369008
def render(self, data, mimetype):
        

        indent = self.__get_indent(mimetype)
        encoding = mimetype.params.get('charset') or 'utf-8'
        return json.dumps(data, indent=indent).encode(encoding)
239650
function base64toBlob(base64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(base64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        return new Blob(byteArrays, {type: contentType});
    }
458628
def parse_render(render):
    
    formats = {
        'jpeg': guess_all_extensions('image/jpeg'),
        'png': guess_all_extensions('image/png'),
        'gif': guess_all_extensions('image/gif'),
        'bmp': guess_all_extensions('image/x-ms-bmp'),
        'tiff': guess_all_extensions('image/tiff'),
        'xbm': guess_all_extensions('image/x-xbitmap'),
        'pdf': guess_all_extensions('application/pdf')
    }
    if not render:
        render = 'png'
    else:
        render = render.lower()
        for k, v in formats.items():
            if '.%s' % render in v:
                render = k
                break
        else:
            render = 'png'
    return render
505022
def inline(width=900):
    
    from IPython.display import Image, HTML, display, clear_output
    import random
    import string
    import urllib
    import os

    while True:
        fname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
        if not os.path.isfile(fname + '.png'):
            break

    savefig(fname)

    if os.path.isfile(fname + '.png'):
        with open(fname + '.png', 'rb') as fin:
            encoded = base64.b64encode(fin.read())
            b64 = urllib.parse.quote(encoded)

        image_html = "<img style='width: %dpx; margin: 0px; float: left; border: 1px solid black;' src='data:image/png;base64,%s' />" % (width, b64)

        display(HTML(image_html))
        os.remove(fname + '.png')
1112187
def image_to_base64(self, image):
        
        if isinstance(image, file_):
            return base64.b64encode(image.read())
        elif isinstance(image, basestring):
            if image.startswith("http"):
                # it's URL
                return base64.b64encode(requests.get(image).content)
            # it's path
            with open(image) as f:
                return base64.b64encode(f.read())

        raise ValueError("Unrecognizable image param: it must one of"
                         " file object, path or URL, not %s" % type(image))
1067321
function base64ToBlob(base64Image, contentType) {
  // http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript

  // Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,'
  base64Image = base64Image.split(',')[1];

  let byteCharacters = atob(base64Image);

  // http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long
  let byteArrays = byteCharacters.match(/[\s\S]{1,512}/g).map( slice => {

    let byteNumbers = slice.split('').map( x => x.charCodeAt(0) );

    return new Uint8Array(byteNumbers);
  });

  let blob = new Blob(byteArrays, { type: contentType || 'image/jpg' /* or 'image/png' */ });

  return blob;
}
475267
protected void render(FacesContext context) throws IOException {

		String src = (String) getAttributes().get("src");
		boolean base64 = Boolean.parseBoolean((String) getAttributes().get("src"));
		String imagePath = getImageUrl(context, src, base64);
		ResponseWriter writer = context.getResponseWriter();
		writer.write(imagePath);
	}
1107621
def render *arguments
      if @_mxit_emulator
        output = render_to_string *arguments
        output = MxitRails::Styles.add_emoticons output
        super :inline => output
      else
        super *arguments
      end
    end
1367808
function renderAsWebP(canvas, quality) {
            var
                frame = canvas.toDataURL('image/webp', {quality: quality});
            
            return decodeBase64WebPDataURL(frame);
        }
766921
def render_template(template_name, context, format='png',
                    output=None, using=None, **options):
    
    # output stream, as required by casperjs_capture
    stream = BytesIO()
    out_f = None
    # the suffix=.html is a hack for phantomjs which *will*
    # complain about not being able to open source file
    # unless it has a 'html' extension.
    with NamedTemporaryFile(suffix='.html') as render_file:
        template_content = render_to_string(
            template_name,
            context,
            using=using,
        )
        # now, we need to replace all occurences of STATIC_URL
        # with the corresponding file://STATIC_ROOT, but only
        # if STATIC_URL doesn't contain a public URI (like http(s))
        static_url = getattr(settings, 'STATIC_URL', '')
        if settings.STATIC_ROOT and\
           static_url and not static_url.startswith('http'):
            template_content = template_content.replace(
                static_url,
                'file://%s' % settings.STATIC_ROOT
            )
        render_file.write(template_content.encode('utf-8'))
        # this is so that the temporary file actually gets filled
        # with the result.
        render_file.seek(0)

        casperjs_capture(
            stream,
            url='file://%s' % render_file.name,
            **options
        )

        # if no output was provided, use NamedTemporaryFile
        # (so it is an actual file) and return it (so that
        # after function ends, it gets automatically removed)
        if not output:
            out_f = NamedTemporaryFile()
        else:
            # if output was provided, write the rendered
            # content to it
            out_f = open(output, 'wb')
        out_f.write(stream.getvalue())
        out_f.seek(0)

        # return the output if NamedTemporaryFile was used
        if not output:
            return out_f
        else:
            # otherwise, just close the file.
            out_f.close()
920051
def _render_image(self, spec, container_args, alt_text=None):
        

        try:
            path, image_args, title = image.parse_image_spec(spec)
        except Exception as err:  # pylint: disable=broad-except
            logger.exception("Got error on spec %s: %s", spec, err)
            return ('<span class="error">Couldn\'t parse image spec: ' +
                    '<code>{}</code> {}</span>'.format(flask.escape(spec),
                                                       flask.escape(str(err))))

        composite_args = {**container_args, **image_args}

        try:
            img = image.get_image(path, self._search_path)
        except Exception as err:  # pylint: disable=broad-except
            logger.exception("Got error on image %s: %s", path, err)
            return ('<span class="error">Error loading image {}: {}</span>'.format(
                flask.escape(spec), flask.escape(str(err))))

        return img.get_img_tag(title, alt_text, **composite_args)
1126094
def embed_image_html(image):
    
    if image is None:
        return None
    elif isinstance(image, PIL.Image.Image):
        pass
    elif isinstance(image, np.ndarray):
        image = PIL.Image.fromarray(image)
    else:
        raise ValueError('image must be a PIL.Image or a np.ndarray')

    # Read format from the image
    fmt = image.format
    if not fmt:
        # default to JPEG
        fmt = 'jpeg'
    else:
        fmt = fmt.lower()

    string_buf = StringIO()
    image.save(string_buf, format=fmt)
    data = string_buf.getvalue().encode('base64').replace('\n', '')
    return 'data:image/%s;base64,%s' % (fmt, data)