Render the base64 corruption
based image glitch effect

@param img
@param options

@returns {{start, stop, clear}}
423499
function imgGlitch(img, options) {
		var imgElement = 'string' === typeof img ? document.querySelector(img) : img;

		if (!(imgElement instanceof HTMLImageElement && imgElement.constructor === HTMLImageElement)) {
			throw new TypeError('renderImgCorruption expects input img to be a valid image element');
		}

		var corrupt64 = getCorrupt64(options);
		var data = imgElement.src;

		var corruption = undefined;

		return {
			start: start,
			stop: stop,
			clear: clear
		};

		/**
   * Start rendering the
   * corruption
   *
   */
		function start() {
			corruption = requestAnimationFrame(render);
		}

		/**
   * Render the corruption
   *
   */
		function render() {
			imgElement.src = corrupt64(data);
			start();
		}

		/**
   * Stop rendering the
   * corruption
   *
   */
		function stop() {
			cancelAnimationFrame(corruption);
		}

		/**
   * Stop rendering the
   * corruption and
   * clear its effects
   *
   */
		function clear() {
			stop();
			imgElement.src = data;
		}
	}
630934
function(options) {
  options = options || {};
  
  this.datasources = [];
  this.styles = [];
  this.projection = DEFAULT_PROJECTION;
  this.assetsPath = ".";
  
  if (options.projection){
    this.projection = projector.util.cleanProjString(options.projection);
    console.log(this.projection);
  }
  
  this.boundsBuffer =
    ("boundsBuffer" in options) ? options.boundsBuffer : BUFFER_RATIO;
  
  this._renderer = cartoRenderer;
}
864938
function pongIOrenderImg( ctx, def ) {
	log( "pong-io", "pongIOrenderImg '"+def.id );
	var background = new Image();	
	if ( def.imgURL && def.pos && def.pos.x && def.pos.y ) {
		background.src = def.imgURL;
		background.onload = function() {
			if ( def.width && def.height ) {
				ctx.drawImage( background, def.pos.x, def.pos.y, def.width, def.height ); 
			} else {
				ctx.drawImage( background, def.pos.x, def.pos.y ); 				
			}
	    };
	}
	log( "pong-io", "pongIOrenderImg end.");
}
762327
public JSONObject imageCensorComb(String imgPath, EImgType type,
                                      List<String> scenes, HashMap<String, String> options) {
        if (type == EImgType.FILE) {
            try {
                byte[] imgData = Util.readFileByBytes(imgPath);
                return imageCensorComb(imgData, scenes, options);
            } catch (IOException e) {
                return AipError.IMAGE_READ_ERROR.toJsonResult();
            }
        }

        // url
        AipRequest request = new AipRequest();

        request.addBody("imgUrl", imgPath);

        return imageCensorCombHelper(request, scenes, options);
    }
24369
protected void renderBitmapImage( BitmapMode mode , ImageBase image ) {
		switch( mode ) {
			case UNSAFE: {
				if (image.getWidth() == bitmap.getWidth() && image.getHeight() == bitmap.getHeight())
					ConvertBitmap.boofToBitmap(image, bitmap, bitmapTmp);
			} break;

			case DOUBLE_BUFFER: {
				// TODO if there are multiple processing threads bad stuff will happen here. Need one work buffer
				// per thread
				// convert the image. this can be a slow operation
				if (image.getWidth() == bitmapWork.getWidth() && image.getHeight() == bitmapWork.getHeight())
					ConvertBitmap.boofToBitmap(image, bitmapWork, bitmapTmp);

				// swap the two buffers. If it's locked don't swap. This will skip a frame but will not cause
				// a significant slow down
				if( bitmapLock.tryLock() ) {
					try {
						Bitmap tmp = bitmapWork;
						bitmapWork = bitmap;
						bitmap = tmp;
					} finally {
						bitmapLock.unlock();
					}
				}
			} break;
		}
	}
549470
public PlanarImage toDirectColorModel(RenderedImage img) {
		BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
		BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img
				.getColorModel().isAlphaPremultiplied(), null);
		ColorConvertOp op = new ColorConvertOp(null);
		op.filter(source, dest);
		return PlanarImage.wrapRenderedImage(dest);
	}
843131
function addWatermark(source, options, callback) {
    var error;

    // check for valid/invalid arguments
    if((arguments.length < 2)
        || (arguments.length  === 2 && !ratify.isFunction(arguments[1]))
        || (arguments.length > 2 && !ratify.isFunction(arguments[2]))) {
        throw new Error('Text-Watermark::addWatermark : Invalid arguments');
    }
    else if(arguments.length === 2 && ratify.isFunction(arguments[1])) {
        callback = arguments[1];
        options = null;
    }

    // if no image source is found
    if(!source || source == "") {
        error = new Error('Text-Watermark::addWatermark : No image source');
        return callback(error);
    }

    // check if source file exists at the specified path
    fs.lstat(source, function(err, stats) {
        if(err) {
            error = new Error('Text-Watermark::addWatermark : Image file doesn\'t exist at source ' + source);
            return callback(error);
        }
        else if(!stats.isFile()) {
            error = new Error('Text-Watermark::addWatermark : Invalid image source at ' + source);
            return callback(error);
        }
        else {
            // use default options if options aren't properly specified
            if(!options || typeof options !== 'object')
                options = defaultOptions;

            im.identify(source, function(err, imageData) {
                if(err) {
                    error = new Error('Text-Watermark::addWatermark : Error while processing image file : ' + err);
                    return callback(error);
                }

                var finalObj = _parseOptions(imageData, source, options);

                im.convert(finalObj.args, function(err, stdout) {
                    if(err) {
                        error = new Error('Text-Watermark::addWatermark : Error in applying watermark : ' + err);
                        return callback(error);
                    }
                    else {
                        console.log('Text-Watermark::addWatermark : Watermark applied. You can check the output file at : ' + finalObj.outputPath);
                        return callback(null);
                    }
                });
            });
        }
    });

    return;
}
542118
function _render_option(){

	var buf = new Array();

	// Sort the items in the mdata array.
	// Also keep a lookup for a "special" entry.
	// var default_on_p = false;
	var mdata_keys = bbop.core.get_keys(anchor.mdata);
	function _data_comp(a, b){

	    // Get the associated data.
	    var a_data = anchor.mdata[a];
	    var b_data = anchor.mdata[b];

	    // if( (a_data['special'] == true && a_data['selected'] == true) ||
	    // 	(b_data['special'] == true && b_data['selected'] == true) ){
	    // 	default_on_p = true;
	    // }

	    //
	    var retval = 0;
	    if( a_data['special'] != b_data['special'] ){
		if( a_data['count'] == true ){
		    retval = 1;
		}else{
		    retval = -1;
		}
	    }else if( a_data['count'] != b_data['count'] ){
		if( a_data['count'] > b_data['count'] ){
		    retval = -1;
		}else{
		    retval = 1;
		}
	    }else if( a_data['label'] != b_data['label'] ){
		if( a_data['label'] > b_data['label'] ){
		    retval = 1;
		}else{
		    retval = -1;
		}
	    }

	    return retval;
	}
	mdata_keys.sort(_data_comp); // inplace sort

	//
	for( var mski = 0; mski < mdata_keys.length; mski++ ){

	    var write_data = anchor.mdata[mdata_keys[mski]];
	    
	    // Write out option if:
	    // 1) the default is selected (so we want to see everything)
	    // 2) the selection is special
	    // 3) if the default is not selected, either the item is selected or
	    // 4) it has a count (and is thus interesting)
	    if( // default_on_p == true ||
	    	write_data['selected'] == true ||
	    	write_data['special'] == true ||
	    	( write_data['count'] && write_data['count'] > 0 ) ){
		    
		    buf.push('<option');
		    // Title.
		    buf.push(' title="');
		    buf.push(write_data['value']);
		    buf.push('"');		
		    // Value.
		    buf.push(' value="');
		    buf.push(write_data['value']);
		    buf.push('"');		
		    if( write_data['selected'] ){
			buf.push(' selected="selected"');
		    }
		    buf.push('>');
		    //buf.push(bbop.core.crop(write_data['label']));
		    buf.push(bbop.core.crop(write_data['label'], 40, '...'));
		    
		    if( write_data['count'] && write_data['count'] > 0 ){
			buf.push(' (' + write_data['count'] + ')');
		    }
		    
		    buf.push('</option>');
		}
		
	}
	return buf.join('');
    }
146015
public static void tileStretchPaint(Graphics g, 
                JComponent comp,
                BufferedImage img,
                Insets ins) {
        
        int left = ins.left;
        int right = ins.right;
        int top = ins.top;
        int bottom = ins.bottom;
        
        // top
        g.drawImage(img,
                    0,0,left,top,
                    0,0,left,top,
                    null);
        g.drawImage(img,
                    left,                 0, 
                    comp.getWidth() - right, top, 
                    left,                 0, 
                    img.getWidth()  - right, top, 
                    null);
        g.drawImage(img,
                    comp.getWidth() - right, 0, 
                    comp.getWidth(),         top, 
                    img.getWidth()  - right, 0, 
                    img.getWidth(),          top, 
                    null);
    
        // middle
        g.drawImage(img,
                    0,    top, 
                    left, comp.getHeight()-bottom,
                    0,    top,   
                    left, img.getHeight()-bottom,
                    null);
        
        g.drawImage(img,
                    left,                  top, 
                    comp.getWidth()-right,      comp.getHeight()-bottom,
                    left,                  top,   
                    img.getWidth()-right,  img.getHeight()-bottom,
                    null);
         
        g.drawImage(img,
                    comp.getWidth()-right,     top, 
                    comp.getWidth(),           comp.getHeight()-bottom,
                    img.getWidth()-right, top,   
                    img.getWidth(),       img.getHeight()-bottom,
                    null);
        
        // bottom
        g.drawImage(img,
                    0,comp.getHeight()-bottom, 
                    left, comp.getHeight(),
                    0,img.getHeight()-bottom,   
                    left,img.getHeight(),
                    null);
        g.drawImage(img,
                    left,                    comp.getHeight()-bottom, 
                    comp.getWidth()-right,        comp.getHeight(),
                    left,                    img.getHeight()-bottom,   
                    img.getWidth()-right,    img.getHeight(),
                    null);
        g.drawImage(img,
                    comp.getWidth()-right,     comp.getHeight()-bottom, 
                    comp.getWidth(),           comp.getHeight(),
                    img.getWidth()-right, img.getHeight()-bottom,   
                    img.getWidth(),       img.getHeight(),
                    null);
    }
648819
function(layer) {
        if (!this.img || !layer) return;

        if (layer.type === "Canvas") {
            this._pattern = this._drawContext.createPattern(
                this.img,
                this._repeat
            );
        } else if (layer.type === "WebGL") {
            this._establishShader(
                "image:" + this.__image,
                Crafty.defaultShader("Image")
            );
            this.program.setTexture(
                this._drawLayer.makeTexture(
                    this.__image,
                    this.img,
                    this._repeat !== "no-repeat"
                )
            );
        }

        if (this._repeat === "no-repeat") {
            this.w = this.w || this.img.width;
            this.h = this.h || this.img.height;
        }

        this.ready = true;
        this.trigger("Invalidate");
    }
852508
private function _output($options = array())
    {
        if (!isset($options["type"])) $options["type"] = "png";
        if (!isset($options["page"])) $options["page"] = 1;
        $type = strtolower($options["type"]);

        if (isset($this->_imgs[$options["page"] - 1])) {
            $img = $this->_imgs[$options["page"] - 1];
        } else {
            $img = $this->_imgs[0];
        }

        // Perform any antialiasing
        if ($this->_aa_factor != 1) {
            $dst_w = $this->_actual_width / $this->_aa_factor;
            $dst_h = $this->_actual_height / $this->_aa_factor;
            $dst = imagecreatetruecolor($dst_w, $dst_h);
            imagecopyresampled($dst, $img, 0, 0, 0, 0,
                $dst_w, $dst_h,
                $this->_actual_width, $this->_actual_height);
        } else {
            $dst = $img;
        }

        switch ($type) {
            case "jpg":
            case "jpeg":
                if (!isset($options["quality"])) {
                    $options["quality"] = 75;
                }

                imagejpeg($dst, null, $options["quality"]);
                break;
            case "png":
            default:
                imagepng($dst);
                break;
        }

        if ($this->_aa_factor != 1) {
            imagedestroy($dst);
        }
    }
468931
function(img, convert_grayscale) {

    if(typeof(convert_grayscale)==='undefined') var convert_grayscale = false;

    var canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");

    // due to a Firefox bug
    try {
      ctx.drawImage(img, 0, 0);
    } catch (e) {
      if (e.name === "NS_ERROR_NOT_AVAILABLE") {
        // sometimes happens, lets just abort
        return false;
      } else {
        throw e;
      }
    }

    try {
      var img_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
    } catch (e) {
      if(e.name === 'IndexSizeError') {
        return false; // not sure what causes this sometimes but okay abort
      } else {
        throw e;
      }
    }

    // prepare the input: get pixels and normalize them
    var p = img_data.data;
    var W = img.width;
    var H = img.height;
    var pv = []
    for(var i=0;i<p.length;i++) {
      pv.push(p[i]/255.0-0.5); // normalize image pixels to [-0.5, 0.5]
    }
    var x = new Vol(W, H, 4, 0.0); //input volume (image)
    x.w = pv;

    if(convert_grayscale) {
      // flatten into depth=1 array
      var x1 = new Vol(W, H, 1, 0.0);
      for(var i=0;i<W;i++) {
        for(var j=0;j<H;j++) {
          x1.set(i,j,0,x.get(i,j,0));
        }
      }
      x = x1;
    }

    return x;
  }
90534
public JSONObject imageCensorUserDefined(byte[] imgData, HashMap<String, String> options) {
        AipRequest request = new AipRequest();

        String base64Content = Base64Util.encode(imgData);
        request.addBody("image", base64Content);

        return imageCensorUserDefinedHelper(request, options);
    }
569155
function svg2ttfTransform(options) {
  // Return a callback function handling the buffered content
  return function svg2ttfTransformCb(err, buf, cb) {

    // Handle any error
    if(err) {
      cb(new gutil.PluginError(PLUGIN_NAME, err, { showStack: true }));
      return;
    }

    // Use the buffered content
    try {
      buf = Buffer.from(svg2ttf(String(buf), {
        ts: options.timestamp,
        copyright: options.copyright,
        version: options.version,
      }).buffer);
    } catch (err2) {
      cb(new gutil.PluginError(PLUGIN_NAME, err2, { showStack: true }));
      return;
    }
    cb(null, buf);
  };
}
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);
   }
686185
private static void displayResults(BufferedImage orig,
									   Planar<GrayF32> distortedImg,
									   ImageDistort allInside, ImageDistort fullView ) {
		// render the results
		Planar<GrayF32> undistortedImg = new Planar<>(GrayF32.class,
				distortedImg.getWidth(),distortedImg.getHeight(),distortedImg.getNumBands());

		allInside.apply(distortedImg, undistortedImg);
		BufferedImage out1 = ConvertBufferedImage.convertTo(undistortedImg, null,true);

		fullView.apply(distortedImg,undistortedImg);
		BufferedImage out2 = ConvertBufferedImage.convertTo(undistortedImg, null,true);

		// display in a single window where the user can easily switch between images
		ListDisplayPanel panel = new ListDisplayPanel();
		panel.addItem(new ImagePanel(orig), "Original");
		panel.addItem(new ImagePanel(out1), "Undistorted All Inside");
		panel.addItem(new ImagePanel(out2), "Undistorted Full View");

		ShowImages.showWindow(panel, "Removing Lens Distortion", true);
	}
785649
function asciifyImage( canvasRenderer, oAscii ) {

		oCtx.clearRect( 0, 0, iWidth, iHeight );
		oCtx.drawImage( oCanvasImg, 0, 0, iWidth, iHeight );
		var oImgData = oCtx.getImageData( 0, 0, iWidth, iHeight ).data;

		// Coloring loop starts now
		var strChars = "";

		// console.time('rendering');

		for ( var y = 0; y < iHeight; y += 2 ) {

			for ( var x = 0; x < iWidth; x ++ ) {

				var iOffset = ( y * iWidth + x ) * 4;

				var iRed = oImgData[ iOffset ];
				var iGreen = oImgData[ iOffset + 1 ];
				var iBlue = oImgData[ iOffset + 2 ];
				var iAlpha = oImgData[ iOffset + 3 ];
				var iCharIdx;

				var fBrightness;

				fBrightness = ( 0.3 * iRed + 0.59 * iGreen + 0.11 * iBlue ) / 255;
				// fBrightness = (0.3*iRed + 0.5*iGreen + 0.3*iBlue) / 255;

				if ( iAlpha == 0 ) {

					// should calculate alpha instead, but quick hack :)
					//fBrightness *= (iAlpha / 255);
					fBrightness = 1;

				}

				iCharIdx = Math.floor( ( 1 - fBrightness ) * ( aCharList.length - 1 ) );

				if ( bInvert ) {

					iCharIdx = aCharList.length - iCharIdx - 1;

				}

				// good for debugging
				//fBrightness = Math.floor(fBrightness * 10);
				//strThisChar = fBrightness;

				var strThisChar = aCharList[ iCharIdx ];

				if ( strThisChar === undefined || strThisChar == " " )
					strThisChar = "&nbsp;";

				if ( bColor ) {

					strChars += "<span style='"
						+ "color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");"
						+ ( bBlock ? "background-color:rgb(" + iRed + "," + iGreen + "," + iBlue + ");" : "" )
						+ ( bAlpha ? "opacity:" + ( iAlpha / 255 ) + ";" : "" )
						+ "'>" + strThisChar + "</span>";

				} else {

					strChars += strThisChar;

				}

			}
			strChars += "<br/>";

		}

		oAscii.innerHTML = "<tr><td>" + strChars + "</td></tr>";

		// console.timeEnd('rendering');

		// return oAscii;

	}