GDI+ BMP转JPG

自己封装的一个函数:

/**
@name    Bmp2Jpg
@brief   BMP转JPG
@param[in]        PBYTE pbBmp
@param[in]        int iBmpLen
@param[in]        PBYTE pbJpg
@param[in]        int * iJpgLen
@return           bool
*/
bool CTest::Bmp2Jpg(PBYTE pbBmp, int iBmpLen, PBYTE pbJpg, int *iJpgLen)
{
    if (pbBmp == NULL || iBmpLen <= 0 || pbJpg == NULL || *iJpgLen <= 0)
    {
        return false;
    }

    // 创建流
    IStream* pStream = NULL;
    CreateStreamOnHGlobal( NULL, TRUE, &pStream);
    if (pStream == NULL)
    {
        return false;
    }

    // 初始化流
    LARGE_INTEGER liTemp = {0};
    ULARGE_INTEGER uLiZero = {0};
    ULONG ulRealSize = 0;
    pStream->Seek(liTemp, STREAM_SEEK_SET,NULL);
    pStream->SetSize(uLiZero);

    pStream->Write(pbBmp, iBmpLen, NULL);  // 把位图放到流中
    Bitmap bmpSrc(pStream);    // 根据流创建位图
    
    // 创建输出流
    IStream* pStreamOut = NULL;
    if (CreateStreamOnHGlobal(NULL, TRUE, &pStreamOut) != S_OK)
    {
        pStream->Release();
        pStream = NULL;
        return false;
    }


    // 初始化输出流
    pStreamOut->Seek(liTemp, STREAM_SEEK_SET, NULL ); 
    pStreamOut->SetSize(uLiZero); 

    // 将位图按照JPG的格式保存到输出流中
    bmpSrc.Save(pStreamOut, &m_jpgClsid, 0);            

    // 获取输出流大小
    bool bRet = false;
    ULARGE_INTEGER libNewPos = {0};
    pStreamOut->Seek(liTemp, STREAM_SEEK_END, &libNewPos);      // 将流指针指向结束位置,从而获取流的大小 
    if (*iJpgLen < (int)libNewPos.LowPart)                     // 用户分配的缓冲区不足
    {
        *iJpgLen = libNewPos.LowPart;
        bRet = false;
    }
    else
    {
        pStreamOut->Seek(liTemp, STREAM_SEEK_SET, NULL);                // 将流指针指向开始位置
        pStreamOut->Read(pbJpg, libNewPos.LowPart, &ulRealSize);        // 将转换后的JPG图片拷贝给用户
        *iJpgLen = ulRealSize;
        bRet = true;
    }


    // 释放内存
    if (pStream != NULL)
    {
        pStream->Release();
        pStream = NULL;
    }
    if (pStreamOut != NULL)
    {
        pStreamOut->Release();
        pStreamOut = NULL;
    }

    return bRet;
}







你可能感兴趣的:(bmp,jpg,GDI+,gdi,图片转换)