Is there are way to manually create a base64code from an image in JS

I draw an image in html canvas.

This is how you calculate the pixels

for (var i = 0; i < data.length; i += 4) {

          var red = data[i]; // red
          var green= data[i + 1]; // green
          var blue = data[i + 2] ; // blue
             }

and this is how you create the base64 code out of it

var dataURL = canvas.toDataURL('image/png');

But this creates base64 code for a png image with RGBa. What do I do to create the base64 code from only the first channel data[i] is there a way to manually encode it to base64 or give the toDataURL options to do so? I tried looking up the documentation but I couldn't find anything

Thanks

EDIT

edit with markE suggestion:

    var imageData = ctx.getImageData(0,0,cw, ch);
     var data= imageData.data        
for (var i = 0; i < data.length; i += 4) {
          var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722;
          data[i]     = grayscale; // red
          data[i + 1] = grayscale; // green
          data[i + 2] = grayscale; // blue
             }


var binary = new Uint8Array(data.length);
for (var i=0; i<data.length; i++){
  binary[i]=data[i];
}
var s=binary.toString();
 var base = btoa(s);

Answers:

Answer

You could:

  1. Save your remaining grayscale values to a Uint8Array,
  2. Stringify that array with var s=myUint8Array.toString(),
  3. Base64 encode that string with btoa(s).

Here's example code:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var img=new Image();
img.crossOrigin = "Anonymous";
img.onload=function(){
  canvas.width=img.width;
  canvas.height=img.height;
  ctx.drawImage(img,0,0);
  var uint8 = new Uint8ClampedArray(img.width*img.height);
  var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
  var data= imageData.data        
  for (var i = 0; i < data.length; i += 4) {
    var grayscale = data[i]*0.2126 + data[i +1]*0.7152 + data[i +2]*0.0722;
    uint8[i]=grayscale;
  }
var s=uint8[0];
for(var i=1;i<uint8.length;i++){
    s+=','+uint8[i];
}
  alert('As string: '+s);
  var b64=btoa(s);
  alert('As base64 string'+b64);
  var ss=atob(b64);
  alert('Back to original string'+ss);
}
img.src='https://dl.dropboxusercontent.com/u/139992952/multple/house16x16.jpg'
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.