Decorator for views that handles ajax image posts in base64 encoding, saving
    the image and returning the url
763472
def handle_image_posts(function=None):
    
    @wraps(function, assigned=available_attrs(function))
    def _wrapped_view(request, *args, **kwargs):
        if 'image' in request.META['CONTENT_TYPE']:
            name = default_storage.save(os.path.join('images', 'aloha-uploads', request.META['HTTP_X_FILE_NAME']),
                                        ContentFile(base64.b64decode(request.body.split(",", 1)[1])))
            return HttpResponse(posixpath.join(settings.MEDIA_URL, name), content_type="text/plain")
        else:
            return function(request, *args, **kwargs)
    return _wrapped_view
178513
def wrap_form_params(func):
    

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "application/x-www-form-urlencoded":
            params = {}
            for key, value in parse_qs(request.body.decode("utf-8")).items():
                if len(value) == 1:
                    params[key] = value[0]
                else:
                    params[key] = value

            request.params = merge_dicts(getattr(request, "params", None), params)
            request.form_params = params
        return func(request, *args, **kwargs)
    return wrapper
431697
def _image_url(array, fmt='png', mode="data", quality=90, domain=None):
  
  supported_modes = ("data")
  if mode not in supported_modes:
    message = "Unsupported mode '%s', should be one of '%s'."
    raise ValueError(message, mode, supported_modes)

  image_data = serialize_array(array, fmt=fmt, quality=quality)
  base64_byte_string = base64.b64encode(image_data).decode('ascii')
  return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
1254416
function POST_FILE(uri, params, filepath) {
	var form = new FormData();

	for (var i in params) {
		form.append(i, params[i]);
	}

	let contenttype = 'INVALID';

	if(filepath.split('.').pop().toLowerCase() == 'jpg') { contenttype = 'image/jpg' }
	if(filepath.split('.').pop().toLowerCase() == 'png') { contenttype = 'image/png' }
	if(filepath.split('.').pop().toLowerCase() == 'gif') { contenttype = 'image/gif' }

	if(contenttype == 'INVALID') { throw 'Invalid image type.' }

	let imageData = fs.readFileSync(filepath);

	form.append('image', imageData, {
		filename: filepath.split('/').pop(),
		filepath: filepath,
		contentType: contenttype,
		knownLength: imageData.length
	});

	const requestURL = `${uri}`;
	log(`request URL: ${requestURL}`);

	return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
    .then(function handleRequest(res) {
			const status = res.status;
			if (status != 200) {
				const error = new Error(`Request failed: ${status}`);
				error.status = status;
				throw error;
			}
			return res.json();
		})
		.catch(error => {
			log(`error: ${error}`);
			throw error;
		});
}
758394
function dataURLToBlob(dataURL) {
                    var BASE64_MARKER = ';base64,',
                        contentType,
                        parts,
                        raw;
                    if (dataURL.indexOf(BASE64_MARKER) === -1) {
                        parts = dataURL.split(',');
                        contentType = parts[0].split(':')[1];
                        raw = parts[1];

                        return new Blob([raw], {type: contentType});
                    }

                    parts = dataURL.split(BASE64_MARKER);
                    contentType = parts[0].split(':')[1];
                    raw = window.atob(parts[1]);
                    var rawLength = raw.length;
                    var uInt8Array = new Uint8Array(rawLength);

                    for (var i = 0; i < rawLength; ++i) {
                        uInt8Array[i] = raw.charCodeAt(i);
                    }
                    return new Blob([uInt8Array.buffer], {type: contentType});
                }
921038
protected void prepareImageUrl(FacesContext context, StringBuffer results) throws IOException {

		String src = (String) getAttributes().get("src");
		boolean base64 = Boolean.parseBoolean((String) getAttributes().get("base64"));
		prepareAttribute(results, "src", getImageUrl(context, src, base64));
	}
1119052
def returns_json(func):
    
    def decorator(*args, **kwargs):
        instance = args[0]
        request = getattr(instance, 'request', None)
        request.response.setHeader("Content-Type", "application/json")
        result = func(*args, **kwargs)
        return json.dumps(result)
    return decorator
161318
function urlToBase64 (url) {
  return new Promise((resolve, reject) => {
    request.get(url, (err, response, body) => {
      err && reject(err)
      resolve(body.toString('base64'))
    })
  })
}
776667
function urlB64ToUint8Array(base64String) {
    const padding = '='.repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
        .replace(/\-/g, '+')
        .replace(/_/g, '/');

    const rawData = self.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}
159554
def apize_raw(url, method='GET'):
	
	def decorator(func):
		def wrapper(*args, **kwargs):
			elem = func(*args, **kwargs)

			if type(elem) is not dict:
				raise BadReturnVarType(func.__name__)

			response = send_request(url, method, 
				elem.get('data', {}),
				elem.get('args', {}),
				elem.get('params', {}),
				elem.get('headers', {}),
				elem.get('cookies', {}),
				elem.get('timeout', 8),
				elem.get('is_json', False),
				elem.get('verify_cert', True)
			)

			return response
		return wrapper

	return decorator
106767
def ajax_only(view_func):
    """"""

    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view(request, *args, **kwargs):
        if request.is_ajax():
            return view_func(request, *args, **kwargs)
        else:
            return http.HttpResponseBadRequest()
    return _wrapped_view
240996
def _needs_base64_encoding(self, attr_type, attr_value):
        
        return attr_type.lower() in self._base64_attrs or \
            isinstance(attr_value, bytes) or \
            UNSAFE_STRING_RE.search(attr_value) is not None
213463
def wrap_multipart_params(func):
    

    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "multipart/form-data":

            if isinstance(pdict['boundary'], str):
                pdict['boundary'] = pdict['boundary'].encode()

            params = {}
            mp = MultipartParser(BytesIO(request.body), pdict['boundary'])
            for part in mp:
                params[part.name] = {
                    "filename": part.filename,
                    "file": part.file,
                }

            request.params = merge_dicts(getattr(request, "params", None), params)
            request.multipart_params = params

        return func(request, *args, **kwargs)
    return wrapper
1287170
def render_data_uri(self, **kwargs):
        """"""
        # Force protocol as data uri have none
        kwargs.setdefault('force_uri_protocol', 'https')
        return "data:image/svg+xml;charset=utf-8;base64,%s" % (
            base64.b64encode(self.render(**kwargs)
                             ).decode('utf-8').replace('\n', '')
        )
59656
def __FinalUrlValue(self, value, field):
        """"""
        if isinstance(field, messages.BytesField) and value is not None:
            return base64.urlsafe_b64encode(value)
        elif isinstance(value, six.text_type):
            return value.encode('utf8')
        elif isinstance(value, six.binary_type):
            return value.decode('utf8')
        elif isinstance(value, datetime.datetime):
            return value.isoformat()
        return value
611271
function toDataURL (image, options) {
  var src = '';
  var async, callback;

  options = options || {};

  async = typeof options.callback === 'function';

  callback = async ? options.callback : function (err, data) {
    if (err) {
      throw err;
    }
    return data;
  };

  function _convert (err, img) {
    if (err) {
      return callback(err);
    }
    var result;
    cors(img);
    result = convert(img, options.width, options.height);
    return callback(null, (options.purify ? purify(result) : result));
  }

  if (isImage(image)) {
    src = image.src || '';
  } else if (typeof image === 'string') {
    if (!async) {
      return callback(new Error('the url mode should be called with a callback'));
    }
    src = image;
  } else {
    return callback(new Error('image should be an Image Object or a string'));
  }

  return async ? createImage(src, _convert) : _convert(null, image);
}
1367808
function renderAsWebP(canvas, quality) {
            var
                frame = canvas.toDataURL('image/webp', {quality: quality});
            
            return decodeBase64WebPDataURL(frame);
        }