// 下载了ijl库,看了看说明文档和例子程序而写下的例子。
#include <windows.h>
#include "ijl.h" // 包含ijl.h文件,并在VC中设置包含入静态ijl15l.lib库或动态ijl15.lib库
// 将hBitmap图像转换成内存DIB数据图像。
BYTE* CreateFromHBITMAP(HBITMAP hBitmap)
{
HDC hdc=GetDC(NULL);
HDC memdc=CreateCompatibleDC(hdc);
SelectObject(memdc,hBitmap);
BITMAP bm;
GetObject(hBitmap,sizeof(BITMAP),&bm);
BITMAPINFO bi;
bi.bmiHeader.biSize=sizeof(bi.bmiHeader);
bi.bmiHeader.biWidth=bm.bmWidth;
bi.bmiHeader.biHeight=bm.bmHeight;
bi.bmiHeader.biPlanes=1;
bi.bmiHeader.biBitCount=24;
bi.bmiHeader.biCompression=BI_RGB;
bi.bmiHeader.biSizeImage=0;
bi.bmiHeader.biXPelsPerMeter=bm.bmWidth;
bi.bmiHeader.biYPelsPerMeter=bm.bmHeight;
bi.bmiHeader.biClrUsed=0;
bi.bmiHeader.biClrImportant=0;
int bitsize=bm.bmWidth*bm.bmHeight*3;
BYTE* buff=new BYTE[sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFO) + bitsize];
BYTE* tmpbuff = buff;
RtlZeroMemory(buff,sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFO) + bitsize);
BITMAPFILEHEADER bf;
bf.bfType=0x4d42;
bf.bfSize=bitsize+14+sizeof(BITMAPINFOHEADER);
bf.bfOffBits=sizeof(bi.bmiHeader)+sizeof(bf);
bf.bfReserved1=0;
bf.bfReserved2=0;
RtlMoveMemory(tmpbuff,&bf,sizeof(BITMAPFILEHEADER));
tmpbuff += sizeof(BITMAPFILEHEADER);
RtlMoveMemory(tmpbuff,&bi,sizeof(BITMAPINFO));
tmpbuff += sizeof(BITMAPINFO);
GetDIBits(memdc,hBitmap,0,bm.bmHeight,tmpbuff,&bi,DIB_PAL_COLORS);
DeleteObject(memdc);
ReleaseDC(0,hdc);
return buff;
}
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInst,
LPSTR lpCmdLine,
int nShowCmd)
{
BYTE* pBuff,*pJpgBuf;
BITMAP bm;
JPEG_CORE_PROPERTIES jcp;
// 自己添加的测试用的图像
HBITMAP hBitmap = LoadBitmap(GetModuleHandle(NULL),(char*)101);
// 将hBitmap图像句柄转换成DIB图像
pBuff = CreateFromHBITMAP(hBitmap);
// 获取图像头信息
GetObject(hBitmap,sizeof(BITMAP),&bm);
// 初始化ijl库
ijlInit(&jcp);
// 初始化ijl JPEG_CORE_PROPERTIES结构
jcp.DIBBytes = (UCHAR *)pBuff;
jcp.DIBHeight = bm.bmHeight;
jcp.DIBWidth = bm.bmWidth;
jcp.DIBPadBytes = IJL_DIB_PAD_BYTES(jcp.DIBWidth,jcp.DIBChannels);
// 新建一个保存转换后的jpg数据缓冲。
pJpgBuf = new BYTE[jcp.DIBWidth * jcp.DIBHeight * 3 + sizeof(BITMAPINFO) + sizeof(BITMAPFILEHEADER)];
// 数据缓冲清零初始化
RtlZeroMemory(pJpgBuf,jcp.DIBWidth * jcp.DIBHeight * 3 + sizeof(BITMAPINFO) + sizeof(BITMAPFILEHEADER));
// 继续初始化ijl JPEG_CORE_PROPERTIES结构
jcp.JPGBytes = pJpgBuf;
jcp.JPGHeight = bm.bmHeight;
jcp.JPGWidth = bm.bmWidth;
jcp.JPGSizeBytes = jcp.DIBWidth * jcp.DIBHeight * 3 + sizeof(BITMAPINFO) + sizeof(BITMAPFILEHEADER);
// 将BMP DIB数据压缩成JPG数据
ijlWrite(&jcp,IJL_JBUFF_WRITEWHOLEIMAGE);
// 创造一个*.jpg文件
HANDLE hFile=CreateFile("a.jpg",GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
DWORD num=0;
SetFilePointer(hFile,0,NULL,0);
// 写入JPG数据到*.jpg文件。
WriteFile(hFile,pJpgBuf,jcp.JPGSizeBytes,&num,NULL);
// 内存BMP DIB数据转换JPG成功,打扫清除对象操作
MessageBox(0,"转换成功!","BMP转JPG",MB_OK);
CloseHandle(hFile);
ijlFree(&jcp);
delete pBuff;
delete pJpgBuf;
return 0;
}
HBITMAP 保存为JPG格式
最新推荐文章于 2022-09-07 18:03:52 发布