MFC 怎么把jpg图转换成单色位图 并保存成图片代码实现
时间: 2023-05-31 14:02:01 浏览: 185
以下是将jpg图转换成单色位图并保存成图片的MFC代码实现:
1. 加载jpg图并创建位图对象
```c++
CImage img;
img.Load(_T("example.jpg")); // 加载jpg图
CBitmap bmp;
bmp.Attach(img.Detach()); // 创建位图对象
```
2. 获取位图信息和像素数据
```c++
BITMAP bmpInfo;
bmp.GetBitmap(&bmpInfo); // 获取位图信息
int width = bmpInfo.bmWidth;
int height = bmpInfo.bmHeight;
BYTE* pPixels = new BYTE[bmpInfo.bmHeight * bmpInfo.bmWidthBytes];
bmp.GetBitmapBits(bmpInfo.bmHeight * bmpInfo.bmWidthBytes, pPixels); // 获取像素数据
```
3. 将像素数据转换成单色位图数据
```c++
BYTE* pMonoPixels = new BYTE[bmpInfo.bmHeight * bmpInfo.bmWidthBytes];
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
BYTE* pPixel = &pPixels[row * bmpInfo.bmWidthBytes + col * 3];
BYTE r = pPixel[0];
BYTE g = pPixel[1];
BYTE b = pPixel[2];
// 灰度值计算公式
BYTE gray = (BYTE)(0.299 * r + 0.587 * g + 0.114 * b);
// 将灰度值转换为单色位图数据
if (gray >= 128)
pMonoPixels[row * bmpInfo.bmWidthBytes + col / 8] |= (0x80 >> (col % 8));
}
}
```
4. 创建单色位图对象并设置位图数据
```c++
BITMAPINFOHEADER bih;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = width;
bih.biHeight = height;
bih.biPlanes = 1;
bih.biBitCount = 1;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
BITMAPINFO bmi;
bmi.bmiHeader = bih;
CBitmap monoBmp;
monoBmp.CreateBitmap(width, height, 1, 1, pMonoPixels);
delete[] pPixels;
delete[] pMonoPixels;
```
5. 保存单色位图为bmp文件
```c++
CImage monoImg;
monoImg.Attach(monoBmp);
monoImg.Save(_T("example_mono.bmp"), Gdiplus::ImageFormatBMP);
```
完整代码:
```c++
CImage img;
img.Load(_T("example.jpg")); // 加载jpg图
CBitmap bmp;
bmp.Attach(img.Detach()); // 创建位图对象
BITMAP bmpInfo;
bmp.GetBitmap(&bmpInfo); // 获取位图信息
int width = bmpInfo.bmWidth;
int height = bmpInfo.bmHeight;
BYTE* pPixels = new BYTE[bmpInfo.bmHeight * bmpInfo.bmWidthBytes];
bmp.GetBitmapBits(bmpInfo.bmHeight * bmpInfo.bmWidthBytes, pPixels); // 获取像素数据
BYTE* pMonoPixels = new BYTE[bmpInfo.bmHeight * bmpInfo.bmWidthBytes];
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
BYTE* pPixel = &pPixels[row * bmpInfo.bmWidthBytes + col * 3];
BYTE r = pPixel[0];
BYTE g = pPixel[1];
BYTE b = pPixel[2];
// 灰度值计算公式
BYTE gray = (BYTE)(0.299 * r + 0.587 * g + 0.114 * b);
// 将灰度值转换为单色位图数据
if (gray >= 128)
pMonoPixels[row * bmpInfo.bmWidthBytes + col / 8] |= (0x80 >> (col % 8));
}
}
BITMAPINFOHEADER bih;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = width;
bih.biHeight = height;
bih.biPlanes = 1;
bih.biBitCount = 1;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
BITMAPINFO bmi;
bmi.bmiHeader = bih;
CBitmap monoBmp;
monoBmp.CreateBitmap(width, height, 1, 1, pMonoPixels);
delete[] pPixels;
delete[] pMonoPixels;
CImage monoImg;
monoImg.Attach(monoBmp);
monoImg.Save(_T("example_mono.bmp"), Gdiplus::ImageFormatBMP);
```
阅读全文