本文演示使用imlib2函数库实现截屏功能
程序运行后,截屏图像保存为jpeg格式文件到当前目录下,起名为“screen.jpeg”
在Debian 5.02系统下,安装libimlib2-dev软件包
imlib2的API文档在 /usr/share/doc/libimlib2-dev/html/index.html
用cvs获取笔者本机screen项目的源代码如下:
$ cvs co -p screen
cvs checkout: Updating screen
===================================================================
Checking out screen/Makefile
RCS: /home/c-aries/cvs/screen/Makefile,v
VERS: 1.2
***************
CC = gcc
CFLAGS = -Wall -Werror -Wcast-align -g
LDFLAGS =
SCREENOBJECT = screen.o
GIBLIBCFLAGS = `giblib-config –cflags`
GIBLIBLIBS = `giblib-config –libs`
all: screen
screen: $(SCREENOBJECT)
$(CC) $(LDFLAGS) $(GIBLIBLIBS) $(SCREENOBJECT) -o $@
screen.o: screen.c screen.h
$(CC) $(CFLAGS) $(GIBLIBCFLAGS) -c $<
clean:
rm -f screen *~ *.o a.out
clean-media:
rm -f *~ *.jpeg
.PHONY: all clean
===================================================================
Checking out screen/screen.c
RCS: /home/c-aries/cvs/screen/screen.c,v
VERS: 1.2
***************
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <giblib/giblib.h>
#include “screen.h”
void
screen_init(struct screen *screen)
{
screen->display = XOpenDisplay(NULL);
if (!screen->display) {
perror(“XOpenDisplay”);
exit(EXIT_FAILURE);
}
screen->screen = ScreenOfDisplay(screen->display,
DefaultScreen(screen->display));
screen->visual = DefaultVisual(screen->display,
DefaultScreen(screen->display));
screen->colormap = DefaultColormap(screen->display,
DefaultScreen(screen->display));
screen->root = RootWindow(screen->display,
DefaultScreen(screen->display));
imlib_context_set_display(screen->display);
imlib_context_set_visual(screen->visual);
imlib_context_set_colormap(screen->colormap);
}
int
main(int argc, char *argv[])
{
struct screen screen;
Imlib_Image image;
screen_init(&screen);
image = gib_imlib_create_image_from_drawable(screen.root,
0,
0,
0,
screen.screen->width,
screen.screen->height,
1);
imlib_context_set_image(image);
imlib_image_set_format(“jpeg”);
imlib_save_image(“screen.jpeg”);
imlib_free_image();
exit(EXIT_SUCCESS);
}
===================================================================
Checking out screen/screen.h
RCS: /home/c-aries/cvs/screen/screen.h,v
VERS: 1.1.1.1
***************
#ifndef SCREEN_H
#define SCREEN_H
#include <X11/Xlib.h>
struct screen {
Display *display;
Screen *screen;
Visual *visual;
Colormap colormap;
Window root;
};
void screen_init(struct screen *screen);
#endif
$
该程序参考了scrot项目的源代码和imlib2的编程文档
上周的文章 video4linux2编程实例 使用video4linux2编程接口获得摄像头数据流,再将YUYV数据流转换成RGB数据流。
然后想添加截取图片功能,将摄像头的RGB数据流保存成JPEG图片。
找来平时一直在使用的自由软件scrot,阅读其源代码,即找到将RGB保存成JPEG图片的方法:
“将用于SDL的像素格式RGBA转换成用于imlib2的像素格式ARGB,再用imlib2的imlib_create_image_using_data()函数保存成JPEG图片”
这部分的代码下周再介绍吧:)
实现截取图片功能的期间,学会了截屏功能……
于是顺便把实现截屏的代码贴出来,作为编程实例。