基本上,当点击一个按钮时,它会告诉移动设备去摄像头。一旦相机拍下照片,它就会给我图像数据(它被称为数据URL吗?)。这是我处理它的代码:
var imagesrc = "data:image/jpeg;base64," + imageData;
var myimage = new Image(500, 500);
myimage.src = imagesrc; <---- to populate the object with the colored image
myimage.src = grayscale(myimage); <---- here I set it to the grayscale image
我想调用一个名为grayscale()
的方法,并使其返回已转换为灰度的图像。我试过这个:
function grayscale(image){
var canvasContext = canvas.getContext('2d');
var imgW = image.width;
var imgH = image.height;
canvas.width = imgW;
canvas.height = imgH;
canvasContext.drawImage(image, 0, 0);
var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
for(>var y = 0; y < imgPixels.height; y++){
for(>var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
dataurl = canvas.toDataURL();
var newimg = "data:image/jpeg;base64," + dataurl;
return newimg;
}
但由于某种原因,它不起作用。它只是不显示灰度图像。我在线获得了for循环代码并对其进行了调整。
这不起作用有几个原因。开始检查控制台输出以跟踪错误对您来说是件好事。例如,Firefox"F12"会告诉您for(>var ...)
有问题。)
您是否在与我们共享的代码之外的某个地方声明了canvas
?是否已声明dataurl
?不需要toDataUrl
的前缀。。。
这是我在for循环中键入的一个基本html文件,它确实将"test.png"变成了灰色。也许你想把它保存在某个地方,把一个png放在同一个文件夹里,然后开始一步一步地编辑东西,而不是复制代码。如果你觉得有挑战,试着让它通过http://jslint.com/!(我想你必须用while循环替换for循环)。:)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas/ImgData Test</title>
</head>
<body>
<canvas id="output"></canvas>
<script>
var cnv = document.getElementById('output');
var cnx = cnv.getContext('2d');
function grey(input) {
cnx.drawImage(myimage, 0 , 0);
var width = input.width;
var height = input.height;
var imgPixels = cnx.getImageData(0, 0, width, height);
for(var y = 0; y < height; y++){
for(var x = 0; x < width; x++){
var i = (y * 4) * width + x * 4;
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
cnx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
}
var myimage = new Image();
myimage.onload = function() {
grey(myimage);
}
myimage.src = "test.png";
</script>
</body>
</html>
我知道您正在寻找将dataURI转换为灰度的,但如果您想将视频反馈本身转换为灰度或将任何图像转换为灰度,可以使用此代码。
.gray {
filter: grayscale();
}
<!--hey use this style to show in gray scale. can even use to convert image to grayscale-->
<video id="camera-stream" class="gray" ></video>
你不应该取这三种颜色分量的平均值,因为它们的亮度变化很大(100%的绿色比100%的蓝色亮得多)。电视系统(PAL和NTSC)将灰度图像的亮度定义为29.9%红色+58.7%绿色+111.4%蓝色。