gpt4 book ai didi

javascript - JS - 如何将Image对象变成灰度并显示

转载 作者:行者123 更新时间:2023-11-30 11:58:53 25 4
gpt4 key购买 nike

基本上,单击按钮时,它会告诉移动设备转到相机。相机拍照后,它会给我图像数据(它叫做数据 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>

关于javascript - JS - 如何将Image对象变成灰度并显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37174616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com