//一个使用CImage类将彩色jpeg图像转换成灰度图像的小程序

//本小程序使用VS2022编程环境,在C++空项目中使用CImage类将彩色jpeg图像转换成灰度图像

//相关代码及注释如下:

#include<iostream>

#include<atlimage.h> //处理图像类对象必须包含的头文件

#include<string.h>

using namespace std;

void ColorToGray(LPCTSTR srcFilePath, LPCTSTR destFilePath)

{

CImage srcImage; //声明图像类对象

srcImage.Load(srcFilePath); //将源图像载入

int width = srcImage.GetWidth(); //获得源图像像素宽度值

int height = srcImage.GetHeight();//获得源图像像素高度值

int bpp = srcImage.GetBPP();

int pitch = srcImage.GetPitch(); //每行字节数

BYTE* pImage = (BYTE*)srcImage.GetBits();//获取图像起始位置指针,GetBits返回的是未定类型,强转一下

cout << "源图像相关信息" << endl;

cout << "图像宽度:" << width << "像素" << endl;

cout << "图像高度:" << height << "像素" << endl;

cout << "分 辨 率:" << width * height / 10000 << "万像素" << endl;

cout << "位 深 度:" << bpp << endl;

system("pause");

for (int x = 0; x < width; x++) //双重循环遍历各像素点

{

for (int y = 0; y < height; y++)

{

BYTE r = *(pImage + pitch * y + x * bpp / 8 + 0);

BYTE g = *(pImage + pitch * y + x * bpp / 8 + 1);

BYTE b = *(pImage + pitch * y + x * bpp / 8 + 2);

//这里指针移动不是通过pImage++自增移动,而是始终以首地址为基准,通过加每行字节(GetPitch)乘行数,

//再加指定位置像素所在列位置(通过GetBPP/8+0/1/2得到,GetBPP得到的是位数值通过除8的到字节数),还

//得加上r、g、b位置。因为像素每行末尾可能存在空字节,所以这种方法比使用pImage++的方法简单。

BYTE gray = round(r * 0.299 + g * 0.587 + b * 0.114);

//彩色图像转换成灰度图像的转换公式

*(pImage + pitch * y + x * bpp / 8 + 0) = gray;

*(pImage + pitch * y + x * bpp / 8 + 1) = gray;

*(pImage + pitch * y + x * bpp / 8 + 2) = gray;

//这里实际是伪转换,图像的大小没有改变,只是r、g、b三个字节都使用相同颜色值。

}

}

srcImage.Save(destFilePath);

//保存转换成灰度的图形

}

int main()

{

LPCTSTR srcFilePath = _T("C:\\Users\\Administrator\\Desktop\\1111.jpg"); //源文件

LPCTSTR destFilePath = _T("C:\\Users\\Administrator\\Desktop\\2222.jpg"); //目标文件

ColorToGray(srcFilePath, destFilePath);

return 0;

}

相关推荐
All for pursuit.2 分钟前
【分治-3】347.前K个高频元素
数据结构·c++·算法·leetcode
头发够用的程序员14 分钟前
TensorRT 自定义算子插件实战(一):从零手写 customScaledTanh
c++·人工智能·pytorch·python·深度学习·边缘计算·jetson
哭泣方源炼蛊19 分钟前
正则表达式c++内容汇集
数据库·c++·mysql·正则表达式
别动我齐刘海30 分钟前
简历技术栈全面复习——UDP / TCP / CAN / ZMQ / Protobuf 通信工程
网络·c++·python·tcp/ip·机器学习·udp·github
All for pursuit.2 小时前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
大侠归来2 小时前
C语言与C++在基础语法上的区别
java·c语言·c++
看看我呀看看我2 小时前
基于Qt的虚拟键盘
c++·qt·qt5·qt6.3
cu1433 小时前
细谈GM8229的具体功能与其应用
c语言·c++·人工智能·单片机
qq_406981034 小时前
c++构造函数初始化列表
c++
王老师青少年编程4 小时前
2026年9月GESP真题及题解(C++八级):末班车
c++·题解·真题·gesp·八级·2026年9月·末班车