在一个字节数组中,例如[40, 0, 156, 243]
,我需要在数组的每个字节的最后两位中产生1个字节。这用于解码和编码PICO-8盒式磁带(see here),它将程序数据存储在PNG图像中。以下是我提供的有关数据存储方式的信息:
For png files, the lower 2 bits of each pixel component makes up one byte, so 1 byte per pixel. The last 32 bytes are metadata for the PNG (since 160*205 = 0x8020, 32 extra bytes)
byte = (a << 6) | (r << 4) | (g << 2) | b;
这是我到目前为止所得到的,但输出都是胡言乱语:
var imgWidth = 160;
var imgHeight = 205;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = document.createElement('img');
img.src = 'Invasion.png';
canvas.width = imgWidth;
canvas.height = imgHeight;
img.onload = function() {
var imgData = [];
var str = '';
var i = 0, n = 0, dataLen = 0;
ctx.drawImage(img, 0, 0);
imgData = ctx.getImageData(0, 0, imgWidth, imgHeight).data;
dataLen = imgData.length;
for(i; i < dataLen; i+=4) {
var r = imgData[i];
var g = imgData[i + 1];
var b = imgData[i + 2];
var a = imgData[i + 3];
r = (r & 3) << 4;
g = (g & 3) << 2;
b = (b & 3);
a = (a & 3) << 6;
byte = a | r | g | b; // assembled byte
str += String.fromCharCode(byte);
}
console.log(str);
};
小提琴:https://jsfiddle.net/24o3fzg3/
非常感谢任何帮助,谢谢!
答案 0 :(得分:4)
要获取最后两位,请尝试value & 3
而不是value % 100
。 (value % 100
在除以十进制的100之后取value
的余数,而不是二进制。)然后,您需要将这两位移到最后一个字节中的适当位置。像这样:
r = (pixels[n][0] & 3) << 4;
g = (pixels[n][1] & 3) << 2;
b = (pixels[n][2] & 3);
a = (pixels[n][3] & 3) << 6;
val = a | r | g | b; // assembled byte
(我没有解决这是否是汇编值中的位或正确的像素数组顺序的正确顺序。)
答案 1 :(得分:1)
我不是一个js家伙,但我认为代码应该是这样的:
...
r = (pixels[n][0] & 3);
g = (pixels[n][1] & 3);
b = (pixels[n][2] & 3);
a = (pixels[n][3] & 3);
byte = (a << 6) | (r << 4) | (g << 2) | b;
str += String.fromCharCode(byte);
...