我想使用 Linux 以最有效的方式获取屏幕像素的 RGB 值。所以我决定使用C中的framebuffer库(fb.h)访问帧缓冲设备(/dev/fb0)并直接从中读取。
这是代码:
#include <stdint.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
int main() {
int fb_fd;
struct fb_fix_screeninfo finfo;
struct fb_var_screeninfo vinfo;
uint8_t *fb_p;
/* Open the frame buffer device */
fb_fd = open("/dev/fb0", O_RDWR);
if (fb_fd < 0) {
perror("Can't open /dev/fb0\n");
exit(EXIT_FAILURE);
}
/* Get fixed info */
if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) < 0) {
perror("Can't get fixed info\n");
exit(EXIT_FAILURE);
}
/* Get variable info */
if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &vinfo) < 0) {
perror("Can't get variable info\n");
exit(EXIT_FAILURE);
}
/* To access to the memory, it can be mapped*/
fb_p = (uint8_t *) mmap(0, finfo.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd, 0);
if (fb_p == MAP_FAILED) {
perror("Can't map memory\n");
exit(EXIT_FAILURE);
}
/* Print each byte of the frame buffer */
for (int i = 0; i < finfo.smem_len; i++) {
printf("%d\n", *(fb_p + i));
// for (int j = 0; j < 500000000; j++); /* Delay */
}
munmap(fb_p, 0);
close(fb_fd);
return 0;
}
但是当我打印这些值时,我没有得到我所期望的......
如果我使用类似的工具选择像素 (0, 0) 的 RGB 值grabc,我明白了:
#85377e
133,55,126
但我的代码的第一个打印是:
126
145
198
...
看起来我很好地获得了第一个像素的第一个值,对应于蓝色,但其余的都是错误的。