从位图中获取像素
我需要在 javascript 中处理来自 1000x1000px *.bmp 图像 (~1MiB) 的像素数据
目前我有点卡住了,因为当我尝试将数据转储到控制台时页面冻结了。
到目前为止的重要代码:
var img = new Image();
img.src = 'image.bmp';
context.drawImage(img, 0, 0);
console.log(context.getImageData(0, 0, canvas.height, canvas.width));
我想这是一个性能问题,但是有没有更好的方法来访问像素数据?我真的不需要一次读取所有内容,逐个读取像素也可以。
编辑:
这是更新的代码,它将用图片的红色值填充二维数组(我正在处理黑白图片,这样就足够了)
var img = new Image();
img.src = 'image.bmp';
context.drawImage(img, 0, 0);
var imgData = context.getImageData(0, 0, canvas.height, canvas.width);
var pixel = new Array();
for(i=0;i<canvas.height;i++){
pixel[i] = new Array();
for(j=0;j<canvas.width;j++){
pixel[i][j] = imgData.data[i*canvas.width+j*4];
}
}
//now pixel[y][x] contains the red-value of the pixel at xy in img
没有性能问题:)唯一的怪癖是行/列被颠倒了
I need to process pixeldata from a 1000x1000px *.bmp image (~1MiB) in javascript
At the moment i am a bit stuck, because the page freezes when i try to dump the data to the console.
the important code so far:
var img = new Image();
img.src = 'image.bmp';
context.drawImage(img, 0, 0);
console.log(context.getImageData(0, 0, canvas.height, canvas.width));
i guess this is a performance issue, but is there a better way to access the pixel data? i dont really need to read it all at once, reading the pixels one by one would also be fine.
EDIT:
here is the updated code, it will populate a 2d-array with the red-value of the picture (i am dealing with a black/white picture, so thats enough)
var img = new Image();
img.src = 'image.bmp';
context.drawImage(img, 0, 0);
var imgData = context.getImageData(0, 0, canvas.height, canvas.width);
var pixel = new Array();
for(i=0;i<canvas.height;i++){
pixel[i] = new Array();
for(j=0;j<canvas.width;j++){
pixel[i][j] = imgData.data[i*canvas.width+j*4];
}
}
//now pixel[y][x] contains the red-value of the pixel at xy in img
no performance issues :) only quirk is that rows/columns are reversed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试创建 1px X 1px 的画布,移动图像,然后读取 imageData
Try creating a canvas of 1px X 1px, move the image and then read the imageData