19,468
社区成员
发帖
与我相关
我的任务
分享
/*************************************************************************
*
* 函数名称:
* SaveJPEG()
*
* 参数:
* HDIB hDIB - DIB 句柄
* CString fileName - 用于保存文件路径和文件名
*
* 返回值:
* void - 无返回值
*
* 说明:
* 该函数对24位DIB位图象进行JPEG编码压缩
*
************************************************************************/
void CMyJPEG::SaveJPEG(HDIB hDIB, CString fileName)
{
// this assumes your data is stored as a 24-bit RGB DIB.
// if you have a 1,4,8,15/16 or 32 bit DIB, you'll have to
// do some work to get it into a 24-bit RGB state.
if (hDIB==NULL) {
AfxMessageBox("图像数据错!");
return;
}
UINT width=0,height=0;
// 定义指向DIB的指针并锁定DIB
LPBYTE lpDIB = (LPBYTE) ::GlobalLock((HGLOBAL) hDIB);
// 读取DIB位图信息头(令指针lpBIH指向DIB位图信息头),获取图像宽度和高度
LPBITMAPINFOHEADER lpBIH=(LPBITMAPINFOHEADER)lpDIB;
width=lpBIH->biWidth;
height=lpBIH->biHeight;
if(lpBIH->biBitCount!=24) //位图不是24位的
{
AfxMessageBox("图像不是24位的!");
// 解除锁定
::GlobalUnlock((HGLOBAL) hDIB);
return;
}
BYTE* buf=m_DIB.FindDIBBits(lpDIB); //获取DIB的位图阵列首地址
BYTE *tmp_buf=NULL;
// assume buf is a DWORD-aligned BGR buffer, vertically flipped
// as if read from a BMP file.
//变量widthBytes用于存放24位位图像一行像素所需的存储空间的大小。
//注:DIB规定以字节为单位的每行长度始终要是4的倍数。
UINT widthBytes=(width*24+31)/32*4;
// un-DWORD-align
tmp_buf=JpegFile::RGBFromDWORDAligned(buf,
width,
widthBytes,
height);
// vertical flip(垂直翻转图像,因为位图像是自下向上存放的,
// 而 JPEG 图像是自上而下存放的。)
JpegFile::VertFlipBuf(tmp_buf, width*3, height);
// reverse BGR(BGR -> RGB)(交换DIB位图阵列中每个像素的红色分量
// 和蓝色分量,得到RGB图像数据。)
JpegFile::BGRFromRGB(tmp_buf, width, height);
if (tmp_buf==NULL) {
AfxMessageBox("~DWORD Memory Error!");
// 解除锁定
::GlobalUnlock((HGLOBAL) hDIB);
return;
}
int quality;
quality=80; // JPEG 文件的质量
// write it(保存RGB图像数据为 JPEG 图像文件)
BOOL ok=JpegFile::RGBToJpegFile(fileName,
tmp_buf,
width,
height,
TRUE,
quality);
if (!ok) {
AfxMessageBox("Write Error!");
}
// 解除锁定
::GlobalUnlock((HGLOBAL) hDIB);
delete [] tmp_buf; //删除存放RGB图像数据的存储空间
}