//一个使用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;

}

相关推荐
咩咦12 小时前
C++学习笔记28:静态成员应用:不用循环求1到n的和
c++·学习笔记·类和对象·static·构造函数·oj·静态成员
EllinY12 小时前
CF2217E Definitely Larger 题解
c++·笔记·算法·构造
筠筠喵呜喵13 小时前
Linux软件开发性能优化
linux·c++·性能优化
Bruce_kaizy13 小时前
c++ linux环境编程——文件io介绍以及open 、write 、read 三剑客深度详解
linux·服务器·c++·ubuntu·操作系统·文件io
PAK向日葵15 小时前
我用 C++ 写了一个轻量级 Python 虚拟机,刚刚开源
c++·python·开源
玖釉-15 小时前
下一个排列:从字典序到原地算法的完整推导
数据结构·c++·windows·算法
枕星而眠16 小时前
数据结构八大排序详解(一):四大简单排序
c语言·数据结构·c++·后端
努力努力再努力wz16 小时前
【Qt入门系列】:按钮组件全解析:从 QAbstractButton 到快捷键事件、单选与复选机制
c语言·开发语言·数据结构·c++·git·qt·github
yunn_17 小时前
单例模式两种实现方法
开发语言·c++·单例模式
代钦塔拉19 小时前
C++ auto
开发语言·c++