看此篇前请先阅读https://blog.csdn.net/qq_20330595/article/details/144134160?spm=1001.2014.3001.5502
stb_image库配置
https://github.com/nothings/stb
代码
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#include <iostream>
void invertColors(unsigned char* img_data, int width, int height, int channels) {
for (int i = 0; i < width * height * channels; i++) {
img_data[i] = 255 - img_data[i]; // 反转颜色
}
}
int main() {
const char* filepath = "IRI_20220322_145855.jpg"; // 图像路径
int width, height, channels;
// 加载图像
unsigned char* img_data = stbi_load(filepath, &width, &height, &channels, 0);
if (img_data == nullptr) {
std::cerr << "Error loading image: " << stbi_failure_reason() << std::endl;
return -1;
}
// 打印基本信息
std::cout << "Image loaded successfully!" << std::endl;
std::cout << "Width: " << width << ", Height: " << height << ", Channels: " << channels << std::endl;
// 反转图像颜色
invertColors(img_data, width, height, channels);
std::cout << "Colors inverted!" << std::endl;
// 保存新的图像
const char* outputFilepath = "output_image.png"; // 输出文件
if (stbi_write_png(outputFilepath, width, height, channels, img_data, width * channels)) {
std::cout << "Image saved successfully as " << outputFilepath << std::endl;
} else {
std::cerr << "Error saving image!" << std::endl;
}
// 释放图像数据
stbi_image_free(img_data);
return 0;
}
运行结果