Ubuntu下CxImage的使用指南
在编译和安装CxImage前,需确保系统具备必要的编译工具和依赖库。打开终端,执行以下命令:
sudo apt update
sudo apt install build-essential libpng-dev libjpeg-dev libtiff-dev libgif-dev
上述命令安装了GCC编译器、CMake构建工具,以及PNG、JPEG、TIFF、GIF等图像格式的支持库。
从CxImage的GitHub仓库克隆最新源码(建议使用main
分支):
git clone https://github.com/cximage/cximage.git
cd cximage
使用CMake生成Makefile并进行编译安装:
mkdir build
cd build
cmake .. # 生成Makefile
make # 编译源码
sudo make install # 安装到系统目录(默认路径:/usr/local/include、/usr/local/lib)
为避免编译时找不到头文件或库文件,可将CxImage的路径添加到环境变量中。编辑~/.bashrc
文件:
echo 'export CPLUS_INCLUDE_PATH=/usr/local/include:$CPLUS_INCLUDE_PATH' >> ~/.bashrc
echo 'export LIBRARY_PATH=/usr/local/lib:$LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc # 使配置立即生效
创建一个C++测试程序(如test_cximage.cpp
),验证图像加载与保存功能:
#include <iostream>
#include "cximage.h"
int main() {
CXImage image;
// 加载图像(替换为你的图像路径,支持JPG、PNG、BMP等格式)
if (!image.Load("input.jpg")) {
std::cerr << "Failed to load image!" << std::endl;
return 1;
}
std::cout << "Image loaded successfully: " << image.GetWidth() << "x" << image.GetHeight() << std::endl;
// 保存为其他格式(如PNG)
if (!image.Save("output.png", CXIMAGE_FORMAT_PNG)) {
std::cerr << "Failed to save image!" << std::endl;
return 1;
}
std::cout << "Image saved as output.png" << std::endl;
return 0;
}
编译并运行程序:
g++ test_cximage.cpp -o test_cximage -lcximage
./test_cximage
若终端输出“Image loaded successfully”和“Image saved as output.png”,则说明CxImage安装成功。
使用CxImage将JPG转换为PNG:
CXImage image;
if (image.Load("input.jpg")) {
image.Save("output.png", CXIMAGE_FORMAT_PNG);
}
CXImage image;
if (image.Load("test.bmp")) {
std::cout << "Format: " << image.GetFormatName() << std::endl;
std::cout << "Width: " << image.GetWidth() << ", Height: " << image.GetHeight() << std::endl;
}
在图像上绘制一个红色像素点:
CXImage image;
if (image.Load("input.png")) {
image.SetPixel(10, 10, 255, 0, 0); // (x, y, R, G, B)
image.Save("output_with_pixel.png", CXIMAGE_FORMAT_PNG);
}
/usr/local/lib
是否在LIBRARY_PATH
中,或手动指定库路径:g++ test_cximage.cpp -o test_cximage -I/usr/local/include -L/usr/local/lib -lcximage