GDI+ 制作透明图片

来源:互联网 发布:淘宝里抢的红包怎么用 编辑:程序博客网 时间:2024/05/05 15:30

1:制作透明图片文件;

      GDI+ 支持32位位图文件,所以自然就支持图片透明了;

       首先:建立一个32位位图文件在内存中,将文件刷新为透明格式;

       其次:在这个内存32位位图文件上作图;

       最后:保存这个32位位图文件为指定格式的图片:

例子如下:在透明位图文件上作图,然后保存问题png格式文件:

#include <GdiPlus.h>
using namespace Gdiplus;
#pragma comment(lib, "Gdiplus")

int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
 UINT  num = 0;          // number of image encoders
 UINT  size = 0;         // size of the image encoder array in bytes

 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;  // Success
  }   
 }

 free(pImageCodecInfo);
 return -1;  // Failure
}

 

 

{

 GdiplusStartupInput gdiplusStartupInput;
 ULONG_PTR           gdiplusToken;
 GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

//1:建立透明内存32位位图文件;
 Bitmap bmp( 1000,1000, PixelFormat32bppARGB );

 

//2:刷新32位位图文件为透明;
 Graphics g( &bmp );

 Color   myColor(0, 0,0,0 ); 
 g.Clear( myColor );  

 

//3:作图:

 g.DrawLine( &Pen(Color::Black), 0,0,100,100);

 

 //4: 显示:

Graphics gwnd(this->m_hWnd);
 gwnd.DrawImage( &bmp, 0,0);

 

//5:保存为png图片:
  CLSID pngClsid;
  GetEncoderClsid(L"image/png", &pngClsid);
  bmp.Save(L"F:\\Mosaic2.png", &pngClsid, NULL);

}

 

2:将指定位图颜色透明:

     1:建立一个32位位图文件在内存中,将指定位图刷新到32为位图文件上;

     2:获取像素点值GetPixel,如果是指定的颜色,设置为透明像素点colorPixel.SetValue( Color::MakeARGB(0,0,0,0) ); SetPixel;

     3:保存图片;

 

注:windows图片查看器,无法产看32位位图透明图片,它会将透明度值取消显示;

但GDI+可以显示32位位图文件;而且其他图片编辑软件可以查看;

原创粉丝点击