libjpeg exit

编译jpeg-9c后得到libjpeg.lib,按照网上的例程,读jpg文件时,只要jpg文件有错误,libjpeg库的函数内部就直接调系统函数exit退出了,这在整合libjpeg库到大型程序里时是绝对不能允许的。仔细查看库里的libjpeg.txt,才知道原来libjpeg能自定义错误处理,例程在example.c文件里的read_JPEG_file。

以下是我整理好的集成接口:
ReadJpg.h

#pragma once
 
HBITMAP readJpegAsBitmap(const char *fileName);

阅读更多libjpeg exit

读取jpg文件到HBITMAP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
HBITMAP loadPictureFromFile(LPCTSTR szFile)
{
	HANDLE hFile = CreateFile(szFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (INVALID_HANDLE_VALUE == hFile)
		return NULL;
 
	DWORD dwFileSize = GetFileSize(hFile, NULL);
 
	LPVOID pvData = NULL;
	HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
 
	pvData = GlobalLock(hGlobal);
 
	DWORD dwBytesRead = 0;
	BOOL bRead = ReadFile(hFile, pvData, dwFileSize, &dwBytesRead, NULL);
	GlobalUnlock(hGlobal);
	CloseHandle(hFile);
 
	LPSTREAM pStm = NULL;
	HRESULT hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pStm);
 
	LPPICTURE gpPicture;
 
	hr = ::OleLoadPicture(pStm, dwFileSize, FALSE, IID_IPicture, (LPVOID *)&gpPicture);
 
	pStm->Release();
 
	OLE_HANDLE picHandle;
	gpPicture->get_Handle(&picHandle);
	HDC hdc = ::CreateCompatibleDC(NULL);
	::SelectObject(hdc, (HGDIOBJ)picHandle);
 
	HBITMAP hRet = (HBITMAP)::GetCurrentObject(hdc, OBJ_BITMAP);
	DeleteDC(hdc);
 
//	gpPicture->Release(); // 这里不能释放gpPicture,否则返回的hRet是野指针数据
 
	return hRet;
}