Skip to content

Instantly share code, notes, and snippets.

@jamen
Created August 4, 2022 01:56
Show Gist options
  • Save jamen/d7a3adad336fbbe17629aa25dac758b0 to your computer and use it in GitHub Desktop.
Save jamen/d7a3adad336fbbe17629aa25dac758b0 to your computer and use it in GitHub Desktop.
use core::slice;
use std::io::{stdout, Write};
use std::ptr::null;
use x11_dl::xlib;
use libvips::{
ops::{pngsave_buffer, BandFormat},
VipsImage,
};
fn main() {
unsafe {
let xlib = x11_dl::xlib::Xlib::open().unwrap();
let display = (xlib.XOpenDisplay)(null());
let screen = (xlib.XDefaultScreen)(display);
let width = (xlib.XDisplayWidth)(display, screen);
if width <= 0 {
panic!("Improper display width returned: {width}")
}
let height = (xlib.XDisplayHeight)(display, screen);
if width <= 0 {
panic!("Improper display height returned: {height}")
}
let root_window = (xlib.XDefaultRootWindow)(display);
let image_raw = (xlib.XGetImage)(
display,
root_window,
0,
0,
width as u32,
height as u32,
u64::MAX,
xlib::ZPixmap,
);
match image_raw as usize as u8 {
xlib::BadDrawable => panic!("XGetImage: BadDrawable"),
xlib::BadMatch => panic!("XGetImage: BadMatch"),
xlib::BadValue => panic!("XGetImage: BadValue"),
_ => {}
}
let image = &mut *image_raw;
if image.byte_order == xlib::MSBFirst {
panic!("Image data in big-endian format is currently unsupported")
}
let bytes_per_pixel = (image.bits_per_pixel / 8) as usize;
let image_size = (image.width * image.height) as usize;
let image_len = image_size * bytes_per_pixel;
let image_data = slice::from_raw_parts_mut(image.data as *mut u8, image_len);
for i in (0..image_len).step_by(4) {
let b = image_data[i];
let r = image_data[i + 2];
image_data[i] = r;
image_data[i + 2] = b;
}
let vips_image =
VipsImage::new_from_memory(image_data, image.width, image.height, 4, BandFormat::Uchar)
.unwrap();
let png = pngsave_buffer(&vips_image).unwrap();
let mut stdout = stdout().lock();
stdout.write_all(&png).unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment