//by @plugnburn
function str2png(datastr) { //string as input, ready compressed PNG data URI as output
var data = unescape(encodeURIComponent(datastr));
var dlen = data.length;
var dim = Math.ceil(Math.sqrt(dlen/3))
var cnv = document.createElement("canvas");
cnv.width=cnv.height=dim;
var ctx=cnv.getContext("2d");
var idata=ctx.createImageData(dim,dim);
var p = -1;
for(var i=0;i<dlen*3;i+=4)
{
idata.data[i]=data.charCodeAt(++p);
idata.data[i+1]=data.charCodeAt(++p);
idata.data[i+2]=data.charCodeAt(++p);
idata.data[i+3]=255;
}
ctx.putImageData(idata,0,0);
return cnv.toDataURL("image/png");
}
function png2str(imglink, cb) { //PNG data URI as input, decompressed string as output (to callback)
var img = new Image();
img.onload = function() {
var cnv = document.createElement("canvas");
var ctx=cnv.getContext("2d");
cnv.width = this.width;
cnv.height = this.height;
ctx.drawImage(this,0,0);
var idata=ctx.getImageData(0,0,this.width,this.height).data;
var data = [];
for(var i=0;i<idata.length;i++)
if(((i+1)&3)&&idata[i]) data.push(String.fromCharCode(idata[i]));
cb(decodeURIComponent(escape(data.join(''))));
}
img.src=imglink;
}
function loadfile(fileobj, cb) { //local file object as input, data URI as output (to callback)
var reader = new FileReader();
reader.onload = function(e){cb(e.target.result)}
reader.readAsDataURL(fileobj);
}