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



edit with markE suggestion:

    var imageData = ctx.getImageData(0,0,cw, ch);
     var 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++){
var s=binary.toString();
 var base = btoa(s);



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";
  var uint8 = new Uint8ClampedArray(img.width*img.height);
  var imageData = ctx.getImageData(0,0,canvas.width,canvas.height);
  var 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;
var s=uint8[0];
for(var i=1;i<uint8.length;i++){
  alert('As string: '+s);
  var b64=btoa(s);
  alert('As base64 string'+b64);
  var ss=atob(b64);
  alert('Back to original string'+ss);
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.