C++ 实现图片变灰处理
借助图像库stb_image实现读取、存储PNG。
stb下载: https://files-cdn.cnblogs.com/files/Kingfans/stb.zip
#include <string> #define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image_write.h" void ColorToGrey(std::string strColorPath, std::string strGreyPath) { int iWidth, iHeight, iTunnel; unsigned char *data = stbi_load(strColorPath.c_str(), &iWidth, &iHeight, &iTunnel, 0); //change pixel switch (iTunnel) { case 3: { for (int dx = 0; dx < iWidth*iHeight; dx++) { unsigned char iRed = data[3 * dx]; unsigned char iGreen = data[3 * dx + 1]; unsigned char iBlue = data[3 * dx + 2]; unsigned char iGray = 0.3*iRed + 0.59*iGreen + 0.11*iBlue; data[3 * dx] = iGray; data[3 * dx + 1] = iGray; data[3 * dx + 2] = iGray; } } break; case 4: { for (int dx = 0; dx < iWidth*iHeight; dx++) { unsigned char iRed = data[4 * dx]; unsigned char iGreen = data[4 * dx + 1]; unsigned char iBlue = data[4 * dx + 2]; unsigned char iAlpha = data[4 * dx + 3]; unsigned char iGray = 0.3*iRed + 0.59*iGreen + 0.11*iBlue; data[4 * dx] = iGray; data[4 * dx + 1] = iGray; data[4 * dx + 2] = iGray; data[4 * dx + 3] = 255; } } break; default: break; } stbi_write_png(strGreyPath.c_str(), iWidth, iHeight, iTunnel, data, iWidth * iTunnel); stbi_image_free(data); } int main() { ColorToGrey("E://1_color.png", "E://1_grey.png"); return 0; }
实现效果: