使用libpng库将XGetImage获取到的内容保存为PNG格式的文件。以下是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <png.h>
void saveImageToPNG(XImage *image, const char *filename) {
FILE *fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Error: Failed to open file '%s' for writing.\n", filename);
return;
}
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
fprintf(stderr, "Error: Failed to create PNG write structure.\n");
fclose(fp);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
fprintf(stderr, "Error: Failed to create PNG info structure.\n");
png_destroy_write_struct(&png_ptr, NULL);
fclose(fp);
return;
}
if (setjmp(png_jmpbuf(png_ptr))) {
fprintf(stderr, "Error: Failed to set PNG jump buffer.\n");
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr, image->width, image->height, 8, PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_write_info(png_ptr, info_ptr);
png_bytep *row_pointers = (png_bytep *)malloc(image->height * sizeof(png_bytep));
for (int y = 0; y < image->height; y++) {
row_pointers[y] = (png_bytep)(image->data + y * image->bytes_per_line);
}
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, NULL);
free(row_pointers);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
int main() {
Display *display = XOpenDisplay(NULL);
if (!display) {
fprintf(stderr, "Error: Failed to open display.\n");
return 1;
}
Window root = DefaultRootWindow(display);
XImage *image = XGetImage(display, root, 0, 0, 1920, 1080, AllPlanes, ZPixmap);
if (!image) {
fprintf(stderr, "Error: Failed to get image from display.\n");
XCloseDisplay(display);
return 1;
}
saveImageToPNG(image, "screenshot.png");
XDestroyImage(image);
XCloseDisplay(display);
return 0;
}