【C语言】之获取显存一帧数据并保存为pnm格式图片

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/fb.h>

int main(int argc, char **argv)
{
	int fd;

	/* 检查参数 */
	if (argc != 2)
	{
		fprintf(stderr, "Usage: ./a.out pnm_file\n");
		return -1;
	}

	/* 打开显存设备 */
	fd = open("/dev/fb0", O_RDWR);
	if (fd < 0)
	{
		perror("opne fb0");
		return -1;
	}

	/* 获取屏幕信息 */
	struct fb_fix_screeninfo fix_info;
	struct fb_var_screeninfo var_info;
	int ret, x, y;
	int line_length;

	ret = ioctl(fd, FBIOGET_FSCREENINFO, &fix_info);
	if (ret < 0)
	{
		perror("ioctl fix_info");
		close(fd);
		return -2;
	}
	ret = ioctl(fd, FBIOGET_VSCREENINFO, &var_info);
	if (ret < 0)
	{
		perror("ioctl var_info");
		close(fd);
		return -3;
	}
	line_length = fix_info.line_length;
	y = var_info.yres; // 屏幕行数
	x = line_length / (var_info.bits_per_pixel / 8); // 屏幕列数

	/* 内存映射:提高速度 */
	unsigned char *fb_addr = mmap(NULL, y * line_length, PROT_READ, MAP_SHARED, fd, 0);
	if (MAP_FAILED == fb_addr)
	{
		perror("mmap");
		close(fd);
		return -4;
	}

	/* 打开目标文件 */
	FILE *fl;
	fl = fopen(argv[1], "w");
	if (NULL == fl)
	{
		fprintf(stderr, "open %s failed!\n", argv[1]);
		munmap(fb_addr, y * line_length);
		close(fd);
		return -5;
	}

	/* 写pnm头 */
	fprintf(fl, "P6\n%d %d\n255\n", x, y);

	/* 
	 * 写rgb数据:
	 * 显存数据存储方式是: B G R A
	 * bmp图片格式为: B G R
	 * 而pnm图片格式是: R G B 
	 */
	int i, j;
	unsigned char *tmp = fb_addr;
	for (i = 0; i < y; i++)
	{
		for (j = 0; j < x; j++)
		{
			fwrite(&tmp[2], 1, 1, fl); // R
			fwrite(&tmp[1], 1, 1, fl); // G
			fwrite(&tmp[0], 1, 1, fl); // B
			tmp += 4;// A
		}
	}

	fclose(fl);
	close(fd);
	munmap(fb_addr, y * line_length);
	return 0;
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值