Javascript如何从图像数据中获取像素颜色

时间:2019-05-06 11:28:30

标签: javascript image pixel

如何从数据中确定图像是什么颜色?我使用Sharp裁剪单个像素以缓冲单个像素:

img.onload = resizeImg;
img.src = 'image.png';

function resizeImg() {
  this.path = this.path = 'image.png';

  sharp(this.path)
  .resize(this.width * 2, this.height * 2)
  .extract({ width: 1, height: 1, left: 250, top: 100 })
  .toBuffer({ resolveWithObject: true })
  .then(({ data, info }) => {
      console.log(data);
  })
}

数据是

单个黑色像素:

0: 137
1: 80
2: 78
3: 71
4: 13
5: 10
6: 26
7: 10
8: 0
9: 0
10: 0
11: 13
12: 73
13: 72
14: 68
15: 82
16: 0
17: 0
18: 0
19: 6
20: 0
21: 0
22: 0
23: 6
24: 8
25: 2
26: 0
27: 0
28: 0
29: 111
30: 174
31: 120
32: 31
33: 0
34: 0
35: 0
36: 9
37: 112
38: 72
39: 89
40: 115
41: 0
42: 0
43: 11
44: 18
45: 0
46: 0
47: 11
48: 18
49: 1
50: 210
51: 221
52: 126
53: 252
54: 0
55: 0
56: 0
57: 12
58: 73
59: 68
60: 65
61: 84
62: 8
63: 215
64: 99
65: 96
66: 160
67: 55
68: 0
69: 0
70: 0
71: 114
72: 0
73: 1
74: 235
75: 156
76: 163
77: 230
78: 0
79: 0
80: 0
81: 0
82: 73
83: 69
84: 78
85: 68
86: 174
87: 66
88: 96
89: 130

还有一个红色像素:

0: 137
1: 80
2: 78
3: 71
4: 13
5: 10
6: 26
7: 10
8: 0
9: 0
10: 0
11: 13
12: 73
13: 72
14: 68
15: 82
16: 0
17: 0
18: 0
19: 6
20: 0
21: 0
22: 0
23: 6
24: 8
25: 2
26: 0
27: 0
28: 0
29: 111
30: 174
31: 120
32: 31
33: 0
34: 0
35: 0
36: 9
37: 112
38: 72
39: 89
40: 115
41: 0
42: 0
43: 11
44: 18
45: 0
46: 0
47: 11
48: 18
49: 1
50: 210
51: 221
52: 126
53: 252
54: 0
55: 0
56: 0
57: 34
58: 73
59: 68
60: 65
61: 84
62: 8
63: 215
64: 99
65: 184
66: 196
67: 200
68: 112
69: 153
70: 145
71: 225
72: 10
73: 3
74: 195
75: 85
76: 24
77: 98
78: 160
79: 166
80: 208
81: 101
82: 70
83: 198
84: 43
85: 140
86: 140
87: 87
88: 25
89: 16
90: 8
91: 0
92: 196
93: 122
94: 29
95: 230
96: 197
97: 156
98: 124
99: 21
100: 0
101: 0
102: 0
103: 0
104: 73
105: 69
106: 78
107: 68
108: 174
109: 66
110: 96
111: 130

仅一个像素缓冲图像的数据并不像我想的那么简单,所以不确定如何识别这些颜色。

1 个答案:

答案 0 :(得分:1)

因为程序没有为data输出明确指定格式,所以sharp生成的输出格式与图像源相同。在这种情况下,输入格式为PNG,因此您的data缓冲区内容也为PNG格式。这就是data的前8个字节是标准PNG文件头的原因,请参见https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header

要获取data输出格式为像素集合,而不考虑图像源的格式,请替换

    .toBuffer({resolveWithObject: true})

使用

    .raw()
    .toBuffer({resolveWithObject: true})