有时候,我们需要不同透明度的图片,使用GDI+可以简单快速做到这一点,今天总结下,把代码贴出来,是基于VS2008开发的。
#include "stdafx.h"
#include <comdef.h>
#include <GdiPlus.h>
#include <iostream>
using namespace Gdiplus;
using namespace std;
#pragma comment(lib,"gdiplus.lib")
int GetEncoderClsid(const WCHAR* format,CLSID* pClsid)
{
UINT num = 0;
UINT size = 0;
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize(&num, &size);
if(size == 0)
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if(pImageCodecInfo == NULL)
return -1; // Failure
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j = 0; j < num; ++j)
{
if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
{
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j;
}
}
free(pImageCodecInfo);
return -1; // Failure
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc!=5)
{
cout<<"参数不够,需要五个参数"<<endl;
return -1;
}
ULONG_PTR gdiToken;
GdiplusStartupInput gdiStartInput;
GdiplusStartup(&gdiToken, &gdiStartInput, NULL);
int Alpha=_wtoi(argv[4]);;
Bitmap img(argv[1]);
int iWidth=img.GetWidth();
int iHeight=img.GetHeight();
Color color,colorTemp;
//依次获取原图像的每一个相素
for(int iRow=0;iRow<iHeight;iRow++){
for(int iColumn=0;iColumn<iWidth;iColumn++){
img.GetPixel(iColumn,iRow,&color);
//重新生成新的像素点
colorTemp.SetValue(color.MakeARGB(Alpha,color.GetR(),color.GetG(),color.GetB()));
//重新设定相素值
img.SetPixel(iColumn,iRow,colorTemp);
}
}
CLSID Clsid;
GetEncoderClsid(argv[3], &Clsid);
img.Save(argv[2], &Clsid);
// GdiplusShutdown(gdiToken);
printf("图像转换成功!\n");
return 0;
}
编译成功后,在dos模式下运行,参数从0到4依次为:程序名,原图像,目标图像,目标图像的格式(比如 image/png ,image/bmp),目标图像的透明度(值的范围为0-255);
比如,以我的为例,生成的SetAlpha.exe文件在E盘的Alpha文件夹下:
开始->运行-》输入cmd->跳转到E:\Alpha目录下:
在E盘的Alpha文件夹下会得到新的图片water2.png;由于上传的结果图在网页中显示效果不好,我就不上图了 。