接着上一篇的程序。下面的一个功能是利用FreeImage将各种格式的图像转换为灰度图像。
方法一:自己写转换函数;
下面的代码就是将各种编码格式的图像转化为灰度图像的处理函数:
FIBITMAP* CGenricImageTransformerView::TransformToGrayscale(FIBITMAP *dib)
{
const int nBitCounts = 8;
int nBpp = FreeImage_GetBPP(dib);
BYTE* imgData = FreeImage_GetBits(dib);
int width = FreeImage_GetWidth(dib);
int height = FreeImage_GetHeight(dib);
FIBITMAP* fiBmp = FreeImage_Allocate(width,height,nBitCounts);
RGBQUAD* pRGBTable = FreeImage_GetPalette(fiBmp);
//创建灰度索引调色板
for (int i = 0;i<256;i++)
{
pRGBTable[i].rgbBlue = i;
pRGBTable[i].rgbGreen = i;
pRGBTable[i].rgbRed = i;
}
BYTE nIntensity;
int j,k;
switch(nBpp)
{
case 32: //32位图(带alpha通道)转换为8位灰度图
for(j=0;j<height;j++)
{
for(k=0;k<4*width;k++)
{
nIntensity = (BYTE)(0.299*imgData[j*4*width+k]+
0.587*imgData[j*4*width+k+1]+0.114*imgData[j*4*width+k+2]);
if(k%4)
FreeImage_SetPixelIndex(fiBmp,k/4,j,&nIntensity);
}
}
return fiBmp;
break;
case 24: //24位图像转为8位灰度图
for(j=0;j<height;j++)
{
for(k=0;k<3*width;k++)
{
nIntensity = (BYTE)(0.299*imgData[j*3*width+k]+
0.587*imgData[j*3*width+k+1]+0.114*imgData[j*3*width+k+2]);
if(k%3)
FreeImage_SetPixelIndex(fiBmp,k/3,j,&nIntensity);
}
}
return fiBmp;
break;
case 8: //8位伪彩色转为8位灰度图
for(j=0;j<height;j++)
{
for(k=0;k<width;k++)
{
FreeImage_GetPixelIndex(dib,k,j,&nIntensity);
RGBQUAD* ptrRGB = FreeImage_GetPalette(dib);
nIntensity = (BYTE)(0.299*ptrRGB[nIntensity].rgbRed+
0.587*ptrRGB[nIntensity].rgbGreen+0.114*ptrRGB[nIntensity].rgbBlue);
FreeImage_SetPixelIndex(fiBmp,k,j,&nIntensity);
}
}
return fiBmp;
break;
default:
break;
}
return NULL;
在菜单栏中新建一个菜单项,设置标签为:转换为灰度图像,并添加命令处理函数:
void CGenricImageTransformerView::OnTransformToGrayscale()
{
// TODO: Add your command handler code here
FIBITMAP* fiBitmap = TransformToGrayscale(dib);
CFileDialog fileDlg(FALSE,".bmp","img.*",OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
"bmp(*.bmp)|*.bmp|jpg(*.jpg)|*.jpg|/
tif(*.tif)|*.tif|png(*.png)|*.png|/
gif(*.gif)|*.gif|Any(*.*)|*.*||",
NULL);
if(IDOK == fileDlg.DoModal())
{
CString filename = fileDlg.GetFileName();
BOOL bSuccess = GenericWriter(fiBitmap,filename);
if(!bSuccess)
MessageBox("Not support that type!");
方法二:直接调用FreeImage库中已经定义好的转换函数:
void CGenricImageTransformerView::OnTransformToGrayscale()
{
// TODO: Add your command handler code here
FIBITMAP* fiBitmap =FreeImage_ConvertToGrayscale(dib);//这里调用FreeImage库中的转换为灰度的函数
CFileDialog fileDlg(FALSE,".bmp","img.*",OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,
"bmp(*.bmp)|*.bmp|jpg(*.jpg)|*.jpg|/
tif(*.tif)|*.tif|png(*.png)|*.png|/
gif(*.gif)|*.gif|Any(*.*)|*.*||",
NULL);
if(IDOK == fileDlg.DoModal())
{
CString filename = fileDlg.GetFileName();
BOOL bSuccess = GenericWriter(fiBitmap,filename);
if(!bSuccess)
MessageBox("Not support that type!");
}
}
用起来也特别方便,除此之外,FreeImage提供了其他的转换函数,可以转换为4位、8位、16位、24位、32位等图像类型。
原文地址:http://blog.csdn.net/summersolstice/article/details/5161859