vc保存HICON为PNG图片文件

BOOL LWHelper::SaveIconToPngFile(HICON hIcon, LPCTSTR lpszPicFileName)
{
    struct _ENCODER_CLSID
    {
        //获取特定图片类型的编码
        static int GetEncoderClsid(const char* format, CLSID* pClsid)
        {
            UINT num = 0, size = 0;

            Gdiplus::GetImageEncodersSize(&num, &size);
            if(size == 0) return -1;  // Failure

            Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(malloc(size));

            Gdiplus::GetImageEncoders(num, size, pImageCodecInfo);
            bool found = false;
            for (UINT ix = 0; !found && ix < num; ++ix) 
            {
                USES_CONVERSION;
                if (stricmp(W2A(pImageCodecInfo[ix].MimeType), format) == 0) 
                {
                    *pClsid = pImageCodecInfo[ix].Clsid;
                    found = true;
                    break;
                }
            }
            free(pImageCodecInfo);
            return found;
        }
    };
    static CLSID encoderCLSID;
    static int nIndex=_ENCODER_CLSID::GetEncoderClsid(_T("image/png"), &encoderCLSID);
    if (nIndex==-1) return FALSE;
    
    if (hIcon == NULL) return FALSE;
    
    ICONINFO icInfo = { 0 };
    if (!::GetIconInfo(hIcon, &icInfo)) return FALSE;
    
    BITMAP bitmap={0}; 
    if(GetObject(icInfo.hbmColor, sizeof(BITMAP), &bitmap)==0)
    {
        DeleteObject(icInfo.hbmColor); 
        DeleteObject(icInfo.hbmMask);
        return FALSE;
    }

    BOOL bResult=FALSE;

    if (bitmap.bmBitsPixel != 32) 
    {
        Gdiplus::Bitmap bmp(hIcon);

#ifdef UNICODE
        Gdiplus::Status st= bmp.Save(lpszPicFileName,&encoderCLSID, NULL);
#else
        USES_CONVERSION;
        Gdiplus::Status st= bmp.Save(A2W(lpszPicFileName),&encoderCLSID, NULL);
#endif // UNICODE
        bResult=st==Gdiplus::Ok;
    } 
    else
    {
        Gdiplus::Bitmap WrapBitmap(icInfo.hbmColor, NULL);

        Gdiplus::BitmapData bitmapData;
        Gdiplus::Rect rcImage(0, 0, WrapBitmap.GetWidth(), WrapBitmap.GetHeight());

        WrapBitmap.LockBits(&rcImage, Gdiplus::ImageLockModeRead, WrapBitmap.GetPixelFormat(), &bitmapData);

        Gdiplus::Bitmap bmp(bitmapData.Width, bitmapData.Height, bitmapData.Stride, PixelFormat32bppARGB, (BYTE*)bitmapData.Scan0);

        WrapBitmap.UnlockBits(&bitmapData);

#ifdef UNICODE
        Gdiplus::Status st= bmp.Save(lpszPicFileName,&encoderCLSID, NULL);
#else
        USES_CONVERSION;
        Gdiplus::Status st= bmp.Save(A2W(lpszPicFileName),&encoderCLSID, NULL);
#endif // UNICODE
        bResult=st==Gdiplus::Ok;
    }
    
    DeleteObject(icInfo.hbmColor); 
    DeleteObject(icInfo.hbmMask);
    
    return bResult;
}

改自:https://blog.csdn.net/chy555chy/article/details/52820118

他使用new,然后在我这有时候莫名奇妙的报内存错误,检测了delete值是正常的也报错=,=改为局部变量正常了

发表评论

电子邮件地址不会被公开。