我有一张1920X1020的JPG图片,想把它变成1024X768的,如果做呢?
代码如下:
/**
@name ScaleJpg
@brief JPG图片缩放
@param[in] PBYTE pbSrc 源图JPG数据
@param[in] int iSrcLen 源图JPG数据长度
@param[in] PBYTE pbDst 目标JPG缓冲区
@param[in] int * iDstLen 目标JPG缓冲区长度
@param[in] int iDstWidth 目标JPG图片宽度,如1024
@param[in] int iDstHeight 目标JPG图片高度,如768
@return bool
*/
bool CTest::ScaleJpg(PBYTE pbSrc, int iSrcLen, PBYTE pbDst, int *iDstLen, int iDstWidth, int iDstHeight)
{
if (pbSrc == NULL || iSrcLen <= 0)
{
return false;
}
if (pbDst == NULL || iDstLen == NULL || *iDstLen <= 0)
{
return false;
}
if (iDstWidth <= 0 || iDstHeight <= 0)
{
return false;
}
// 创建流
IStream *pstmp = NULL;
CreateStreamOnHGlobal(NULL, TRUE, &pstmp);
if (pstmp == NULL)
{
return false;
}
// 初始化流
LARGE_INTEGER liTemp = {0};
ULARGE_INTEGER uLiZero = {0};
pstmp->Seek(liTemp, STREAM_SEEK_SET,NULL);
pstmp->SetSize(uLiZero);
// 将图像放入流中
ULONG ulRealSize = 0;
pstmp->Write(pbSrc, iSrcLen, &ulRealSize);
// 从流创建位图
Bitmap bmpSrc(pstmp);
Bitmap bmpDst(iDstWidth, iDstHeight, PixelFormat24bppRGB);
// 创建画图对象
Graphics grDraw(&bmpDst);
// 绘图
grDraw.DrawImage(&bmpSrc, 0, 0, bmpSrc.GetWidth(), bmpSrc.GetHeight());
if (Ok != grDraw.GetLastStatus())
{
pstmp->Release();
pstmp = NULL;
return false;
}
// 创建输出流
IStream* pStreamOut = NULL;
if (CreateStreamOnHGlobal(NULL, TRUE, &pStreamOut) != S_OK)
{
pstmp->Release();
pstmp = NULL;
return false;
}
// 初始化输出流
pStreamOut->Seek(liTemp, STREAM_SEEK_SET, NULL );
pStreamOut->SetSize(uLiZero);
// 将位图按照JPG的格式保存到输出流中
bmpDst.Save(pStreamOut, &m_jpgClsid, 0);
// 获取输出流大小
bool bRet = false;
ULARGE_INTEGER libNewPos = {0};
pStreamOut->Seek(liTemp, STREAM_SEEK_END, &libNewPos); // 将流指针指向结束位置,从而获取流的大小
if (*iDstLen < (int)libNewPos.LowPart) // 用户分配的缓冲区不足
{
*iDstLen = libNewPos.LowPart;
bRet = false;
}
else
{
pStreamOut->Seek(liTemp, STREAM_SEEK_SET, NULL); // 将流指针指向开始位置
pStreamOut->Read(pbDst, libNewPos.LowPart, &ulRealSize); // 将转换后的JPG图片拷贝给用户
*iDstLen = ulRealSize;
bRet = true;
}
// 释放内存
if (pstmp != NULL)
{
pstmp->Release();
pstmp = NULL;
}
if (pStreamOut != NULL)
{
pStreamOut->Release();
pStreamOut = NULL;
}
return bRet;
}