我在html画布中绘制图像。
这是计算像素的方法
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
}
这就是你用它创建base64代码的方法
var dataURL = canvas.toDataURL('image/png');
但这会为带有RGBa的png图像创建base64代码。如何仅从第一个通道data[i]
创建base64代码有没有办法手动将其编码为base64或者给toDataURL选项这样做?我试着查看文档,但我找不到任何东西
由于
修改
使用markE建议进行编辑:
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);
答案 0 :(得分:1)
你可以:
Uint8Array
,var s=myUint8Array.toString()
,btoa(s)
编码该字符串。以下是示例代码:
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'
&#13;
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;