javascript-如何将图像(PNG)转换为2D数组(二进制图像)?
作者:互联网
我需要以下PNG图像的2D二进制表示形式:
谁能提供一种方法或源将上面的PNG图像转换为1 =土地而0 =水的2D阵列?
通过一些阅读,我找到了一种使用在线Base64ImageEncoder将图像转换为base64之后循环遍历图像中所有像素的方法.
使用以下fiddle,我能够确定像素是水还是陆地,然后更改像素颜色,因此输出为:
我觉得我已经很接近获得我真正需要的东西了.我需要怎么做才能更改主for循环,而不是将数据保存在Matrix内?
JavaScript的:
$(document).ready(function() {
$("#btnSubmit").click(function(){
GetBinary();
});
});
function GetBinary() {
var canvas = document.createElement("canvas");
canvas.width = imgElement.offsetWidth;
canvas.height = imgElement.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElement,0,0);
var map = ctx.getImageData(0,0,canvas.width,canvas.height);
var imdata = map.data;
var r,g,b;
for(var p = 0, len = imdata.length; p < len; p+=4) {
r = imdata[p]
g = imdata[p+1];
b = imdata[p+2];
if ((r >= 164 && r <= 255) && (g >= 191 && g <= 229) && (b >= 220 && b <= 255)) {
// black = water
imdata[p] = 0;
imdata[p+1] = 0;
imdata[p+2] = 0;
} else {
// white = land
imdata[p] = 255;
imdata[p+1] = 255;
imdata[p+2] = 255;
}
}
ctx.putImageData(map,0,0);
imgElement.src = canvas.toDataURL();
}
请注意,我使用的是base64图像,因此我们不能在此处粘贴它,因为它太长了.请my fiddle代替.
HTML:
<img id='myImage' src='base64 image data' />
<br />
<input id = "btnSubmit" type="button" value="Get Binary Image"/>
解决方法:
看起来图像数据返回的是rgba组件的单个数组,您只需要将其分成几行即可.查看http://jsfiddle.net/mendesjuan/wjn0dub7/1/
var currentInnerArray;
var zeroesAndOnes = [];
for(var p = 0, len = imdata.length; p < len; p+=4) {
r = imdata[p]
g = imdata[p+1];
b = imdata[p+2];
// Each line is the pixel width * 4, (rgba), start a newline
if (p % imdata.width * 4 === 0) {
currentInnerArray = [];
zeroesAndOnes.push(currentInnerArray);
}
if ((r >= 164 && r <= 255) && (g >= 191 && g <= 229) && (b >= 220 && b <= 255)) {
currentInnerArray.push(0);
// black = water
imdata[p] = 0;
imdata[p+1] = 0;
imdata[p+2] = 0;
} else {
currentInnerArray.push(1);
// white = land
imdata[p] = 255;
imdata[p+1] = 255;
imdata[p+2] = 255;
}
}
// zeroesAndOnes has your 2d array
标签:javascript,google-maps,binary-data 来源: https://codeday.me/bug/20191009/1879332.html