PNGeek: library for client-side PNG compression


SUBMITTED BY: Guest

DATE: Dec. 7, 2012, 7:36 a.m.

FORMAT: JavaScript

SIZE: 1.5 kB

HITS: 1259

  1. //by @plugnburn
  2. function str2png(datastr) { //string as input, ready compressed PNG data URI as output
  3. var data = unescape(encodeURIComponent(datastr));
  4. var dlen = data.length;
  5. var dim = Math.ceil(Math.sqrt(dlen/3))
  6. var cnv = document.createElement("canvas");
  7. cnv.width=cnv.height=dim;
  8. var ctx=cnv.getContext("2d");
  9. var idata=ctx.createImageData(dim,dim);
  10. var p = -1;
  11. for(var i=0;i<dlen*3;i+=4)
  12. {
  13. idata.data[i]=data.charCodeAt(++p);
  14. idata.data[i+1]=data.charCodeAt(++p);
  15. idata.data[i+2]=data.charCodeAt(++p);
  16. idata.data[i+3]=255;
  17. }
  18. ctx.putImageData(idata,0,0);
  19. return cnv.toDataURL("image/png");
  20. }
  21. function png2str(imglink, cb) { //PNG data URI as input, decompressed string as output (to callback)
  22. var img = new Image();
  23. img.onload = function() {
  24. var cnv = document.createElement("canvas");
  25. var ctx=cnv.getContext("2d");
  26. cnv.width = this.width;
  27. cnv.height = this.height;
  28. ctx.drawImage(this,0,0);
  29. var idata=ctx.getImageData(0,0,this.width,this.height).data;
  30. var data = [];
  31. for(var i=0;i<idata.length;i++)
  32. if(((i+1)&3)&&idata[i]) data.push(String.fromCharCode(idata[i]));
  33. cb(decodeURIComponent(escape(data.join(''))));
  34. }
  35. img.src=imglink;
  36. }
  37. function loadfile(fileobj, cb) { //local file object as input, data URI as output (to callback)
  38. var reader = new FileReader();
  39. reader.onload = function(e){cb(e.target.result)}
  40. reader.readAsDataURL(fileobj);
  41. }

comments powered by Disqus