The CImg Library is a lightweight, header-only C++ toolkit for image processing. It is popular because it does not require complex installation—you simply include CImg.h in your project. Core Setup
To use CImg, download CImg.h, place it in your project folder, and include it.
#define cimg_use_jpeg // Define before include if using JPEG (requires libjpeg) #define cimg_use_png // Define before include if using PNG (requires libpng) #include “CImg.h” using namespace cimg_library; Use code with caution. 1. Loading Images
You instantiate a CImg object by passing the file path to the constructor. BMP support: Works out of the box with zero dependencies.
PNG/JPEG support: Requires linking external libraries (libpng, libjpeg) and defining the macros shown above.
// Load a standard BMP image CImg Use code with caution. 2. Manipulating Images
CImg provides intuitive methods for pixel-level modification, resizing, and color conversion. Pixel Manipulation
Pixels are accessed using (x, y, z, c), where z is the depth slice (for 3D images) and c is the color channel (0=Red, 1=Green, 2=Blue).
// Invert colors of the image cimg_forXY(image, x, y) { image(x, y, 0, 0) = 255 - image(x, y, 0, 0); // Red image(x, y, 0, 1) = 255 - image(x, y, 0, 1); // Green image(x, y, 0, 2) = 255 - image(x, y, 0, 2); // Blue } Use code with caution. Common Operations
// Resize image to 800x600 pixels image.resize(800, 600); // Convert a color image to grayscale CImg Use code with caution. 3. Saving Images
Saving an image uses the .save() method. CImg determines the output format automatically based on the file extension.
// Save as a BMP file image.save(“output.bmp”); // Save as a PNG file (requires libpng setup) image.save(“output.png”); Use code with caution. Complete Example: Loading, Grayscale, and Saving
Here is a complete, minimal program that loads a BMP image, turns it into a grayscale image, and saves it.
#include “CImg.h” using namespace cimg_library; int main() { try { // 1. Load CImg Use code with caution. Compilation Note
When compiling on Linux/macOS with X11 display capabilities, you need to link the X11 library:
g++ -o main main.cpp -O2 -L/usr/X11R6/lib -lm -lpthread -lX11 Use code with caution.
If you do not need display windows and want to avoid X11 errors, define cimg_display=0 before including the header. To help you get this running smoothly, let me know: What operating system and compiler are you using? Do you need to support PNG/JPG files, or is BMP enough?
Leave a Reply