GDI+ 将BMP 32图像转换为JPG文件格式保存

注意:如果没有启动GDI +, 在lockbits 时会返回失败!

1.在stdafx.h 中加入 

#define ULONG_PTR unsigned long
#include

using namespace Gdiplus;


2.在头文件中定义变量:

ULONG_PTR        m_gdiplusToken;


3.在类初始化或启动时:

GdiplusStartupInput     m_gdiplusStartupInput;
GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);//启动gdi+


4.在析构或停止函数中

Gdiplus::GdiplusShutdown(m_gdiplusToken); //停止GDI+


5.增加函数:



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   
}


6. 转换后保存文件函数

long PlaybackWindow::SnapshotJPGFile(LPCTSTR bstrFilename)
{


long width = 0;
long height = 0;
long bits = 0;
int quality = JPG_QUALITY; //压缩质量,0 ~ 100,建议50
int ret = 0;


long frameSize = 0;

if(!m_pGrabberSetting)
{
return 0;
}


HRESULT hr=m_pGrabberSetting->get_ImageSize(&width,&height,&bits); //获取视频长宽和位深度
if (hr != S_OK)
{
return 0;
}




if (!GetFrameSize(&frameSize))//获取视频缓冲大小
{
return 0;
}


BYTE * pBuffer = new BYTE[frameSize];
if (pBuffer == NULL)
{
return 0;
}


hr=m_pGrabberSetting->Snapshot(pBuffer, TRUE);
if (hr != S_OK)
{
delete [] pBuffer;
return 0;
}




Bitmap bit_map(width,height);


Rect rect( 0, 0, width, height );


BitmapData    *pBitmapData = new BitmapData;


if(pBitmapData == NULL)
{
delete [] pBuffer;
return 0;
}


ret = bit_map.LockBits(&rect, ImageLockModeWrite, PixelFormat32bppRGB, pBitmapData ); //锁定缓冲区


memcpy(pBitmapData->Scan0,pBuffer,frameSize); //将BMP 数据拷贝过来。


bit_map.UnlockBits( pBitmapData ); //解锁缓冲区


CLSID               encoderClsid;   
EncoderParameters   encoderParameters;   


encoderParameters.Count   =   1;   
encoderParameters.Parameter[0].Guid   =   EncoderQuality;   
encoderParameters.Parameter[0].Type   =   EncoderParameterValueTypeLong;   
encoderParameters.Parameter[0].NumberOfValues   =   1;   
encoderParameters.Parameter[0].Value   =   &quality;   


GetEncoderClsid(L"image/jpeg",   &encoderClsid);   //JPG 压缩


bit_map.Save(bstrFilename,   &encoderClsid,   &encoderParameters); //保存文件


if(pBitmapData)
delete pBitmapData;


if (pBuffer)
delete []pBuffer;


return 1;
}

你可能感兴趣的:(dshow,视频解码)