使用IPicture介面讀取和顯示BMP,GIF,JPG,ICO,EMF,WMF影像 (轉)
問題的起源
很久以來,我都被一個問題困擾。關於中顯示影像的問題,我在上搜尋了很長時間,找到了無數的解決方案,比如分析格式,直接讀取檔案的;用的(ImgEdit);以及不知道內部實現方法的庫(ImageLoad)。而我找到的方法大都不容易使用,特別是那些直接按位讀取影像的。很多時候我不得不為每種檔案格式寫一段程式碼。
目前我的解決方案
在使用了多種圖形顯示方案之後,我決定使用提供的IPicture介面來顯示影像。由於MFC的CPictureHolder類是這個介面的一個封裝,而且自帶了從影像控制程式碼讀入圖形的功能,所以我的工作以CPictureHolder類為基礎。要是你不喜歡MFC的話,你可以把CPictureHolder類的程式碼從MFC的裡面分離出來單獨使用。
CPictureHolder類的設計目的是實現控制元件的Picture屬性,允許在控制元件中顯示影像。作為預設的Picture屬性,開發者可以指定一個點陣圖(Bitmap),圖示(Icon),或者圖元檔案(Metafile)來顯示。雖然微軟的文件中並未說明支援JPEG格式的影像,但是經過我的測試,在98以上,以及中,它實際上是支援JPEG格式的,根據微軟的文件,支援的影像格式有BMP,DIB,WMF,ICO。筆者並未測試其他影像格式是否被支援,例如PNG、GIF、PCX等等,有興趣的讀者可以去自己測試一下。(據111222的文件/develop/read_article.?id=10632">http://www.csdn.net/develop/read_article.asp?id=10632,也支援GIF格式)
由於CPictureHolder類並未實現從檔案/資源/讀入影像,使用起來很不方便,所以我擴充套件了這個類以支援上述功能。部分工作基於Dr. Yovav Gad, (to:s@SuperMain.com">Sources@SuperMain.com ,)和的程式碼。
要使用CPictureHolder類,必須先包含afxctl.h
原始碼
#include
class CPicture:public CPictureHolder
{
public:
BOOL Load(CString ilePathName);//從檔案讀取影像
BOOL Load(HINSTANCE hInstance,LPCTSTR lpszResourceName, LPCSTR ResourceType);//從資源讀取影像
BOOL LoadPictureData(BYTE* pBuffer, int nSize);//從記憶體讀取影像
BOOL SaveAsBitmap(CString sFilePathName);//寫入到BMP檔案
void Render(CDC* pDC, LPRECT pDrawRect/*目標矩形,單位是邏輯座標單位*/, LPRECT
pSrcRect=NULL/*來源矩形,單位是0.01毫米,如果為空,則拉伸整個影像到目標矩形*/,LPCRECT prcWBounds=NULL/*圖元檔案專用,繫結矩形*/);//在給定的DC上畫圖,
CPicture();
virtual ~CPicture();
void UnloadPicture();//釋放影像,作用同CPictureHolder::~CPictureHolder()
public:
LONG get_Height(); // 以0.01毫米為單位的影像高度
LONG get_Width(); // 以0.01毫米為單位的影像寬度
};
//-----------------------------------------------------------------------------
// Does: Free The Allocated Memory That Holdes The IPicture Interface Data
// ~~~~ And Clear Picture Information
//
// Note: This Might Also Be Useful If U Only Need To Show The Picture Once
// ~~~~~ Or If U Copy The Picture To The Device Context, So It Can Still
// Remain On Screen - But IPicture Data Is Not Needed No More
//
//-----------------------------------------------------------------------------
void CPicture::UnloadPicture()
//=============================================================================
{
if(m_pPict != NULL){
m_pPict->Release();
m_pPict = NULL;
}
}
//-----------------------------------------------------------------------------
// Does: Open a Resource And Load It Into IPicture (Interface)
// ~~~~ (.BMP .DIB .EMF .GIF .ICO .JPG .WMF)
//
// Note: When Adding a Bitmap Resource It Would Automatically Show On "Bitmap"
// ~~~~ This NOT Good Coz We Need To Load It From a Custom Resource "BMP"
// To Add a Custom Rresource: Import Resource -> Open As -> Custom
// (Both .BMP And .DIB Should Be Found Under "BMP")
//
// InPut: ResourceName - As a UINT Defined (Example: IDR_PICTURE_RESOURCE)
// ~~~~~ ResourceType - Type Name (Example: "JPG")
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture::Load(HINSTANCE hInstance,LPCTSTR lpszResourceName, LPCSTR ResourceType)
//=============================================================================
{
HGLOBAL hGlobal = NULL;
HRSRC hSource = NULL;
LPVOID lpVoid = NULL;
int nSize = 0;
BOOL bResult=FALSE;
if(m_pPict != NULL) UnloadPicture(); // Important - Avoid Leaks...
hSource = FindResource(hInstance, lpszResourceName, ResourceType);
if(hSource == NULL)
{
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "FindResource() Failedt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
return(FALSE);
}
hGlobal = LoadResource(hInstance, hSource);
if(hGlobal == NULL)
{
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "LoadResource() Failedt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
return(FALSE);
}
lpVoid = LockResource(hGlobal);
if(lpVoid == NULL)
{
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "LockResource() Failedt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
return(FALSE);
}
nSize = (UINT)SizeofResource(hInstance, hSource);
if(LoadPictureData((BYTE*)hGlobal, nSize)) bResult = TRUE;
UnlockResource(hGlobal); // 16Bit Windows Needs This
FreeResource(hGlobal); // 16Bit Windows Needs This (32Bit - Automatic Release)
return(bResult);
}
//-----------------------------------------------------------------------------
// Does: Open a File And Load It Into IPicture (Interface)
// ~~~~ (.BMP .DIB .EMF .GIF .ICO .JPG .WMF)
//
// InPut: sFilePathName - Path And FileName Target To Save
// ~~~~~
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture::Load(CString sFilePathName)
//=============================================================================
{
if(!PathFileExists(sFilePathName))return FALSE;
BOOL bResult = FALSE;
CFile PictureFile;
CFileException e;
int nSize = 0;
if(m_pPict != NULL) UnloadPicture(); // Important - Avoid Leaks...
if(PictureFile.Open(sFilePathName, CFile::modeRead | CFile::typeBinary, &e))
{
nSize = PictureFile.GetLength();
BYTE* pBuffer = new BYTE[nSize];
if(PictureFile.Read(pBuffer, nSize) > 0)
{
if(LoadPictureData(pBuffer, nSize)) bResult = TRUE;
}
PictureFile.Close();
delete [] pBuffer;
}
else // Open Failed...
{
TCHAR szCause[255];
e.GetErrorMessage(szCause, 255, NULL);
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, szCause, ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
bResult = FALSE;
}
return(bResult);
}
//-----------------------------------------------------------------------------
// Does: Read The Picture Data From a Source (File / Resource)
// ~~~~ And Load It Into The Current IPicture In Use
//
// InPut: Buffer Of Data Source (File / Resource) And Its Size
// ~~~~~
//
// OutPut: Feed The IPicture Object With The Picture Data
// ~~~~~~ (Use Draw Functions To Show It On a Device Context)
// TRUE If Succeeded...
//-----------------------------------------------------------------------------
BOOL CPicture::LoadPictureData(BYTE *pBuffer, int nSize)
//=============================================================================
{
BOOL bResult = FALSE;
HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, nSize);
if(hGlobal == NULL)
{
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "Can not allocate enough memoryt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
return(FALSE);
}
void* pData = GlobalLock(hGlobal);
memcpy(pData, pBuffer, nSize);
GlobalUnlock(hGlobal);
IStream* pStream = NULL;
if(CreateStreamOnHGlobal(hGlobal, TRUE, &pStream) == S_OK)
{
HRESULT hr;
if((hr = OleLoadPicture(pStream, nSize, FALSE, IID_IPicture, (LPVOID *)&m_pPict)) == E_NOINTERFACE)
{
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "IPicture interface is not supportedt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
return(FALSE);
}
else // S_OK
{
pStream->Release();
pStream = NULL;
bResult = TRUE;
}
}
FreeResource(hGlobal); // 16Bit Windows Needs This (32Bit - Automatic Release)
return(bResult);
}
//-----------------------------------------------------------------------------
// Does: Draw The Loaded Picture Direct To The Client DC
// ~~~~
//
// Note: Bigger OR Smaller Dimentions Than The Original Picture Size
// ~~~~ Will Draw The Picture Streached To Its New Given NEW Dimentions...
//
// InPut: pDC - Given DC To Draw On
// ~~~~~ pSrcRect- Dimentions Of The Picture To Draw From(As a Rectangle)
// DrawRect - Dimentions Of The Picture To Draw To(As a Rectangle)
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
//=============================================================================
void CPicture::Render(CDC* pDC, LPRECT pDrawRect, LPRECT pSrcRect/*=NULL*/,LPCRECT prcWBounds/*=NULL*/)
{
if (pDC == NULL || m_pPict == NULL) return ;
CRect recrDest(pDrawRect);
long Width = 0;
long Height = 0;
m_pPict->get_Width(&Width);
m_pPict->get_Height(&Height);
CRect SrcRect(0,0,Width,Height);
if(pSrcRect){
SrcRect=*pSrcRect;
}
CRect DrawRect(pDrawRect);
HRESULT hrP = NULL;
hrP = m_pPict->Render(pDC->m_hDC,
DrawRect.left, // Left
DrawRect.top, // Top
DrawRect.Width(), // Right
DrawRect.Height(), // Bottom
SrcRect.left,
SrcRect.top,
SrcRect.Width(),
SrcRect.Height(),
prcWBounds);
if (SUCCEEDED(hrP)) return;
AfxThrowMemoryException();
return;
}//-----------------------------------------------------------------------------
// Does: Saves The Picture That Is Stored In The IPicture Object As a Bitmap
// ~~~~ (Converts From Any Known Picture Type To a Bitmap / Icon File)
//
// InPut: sFilePathName - Path And FileName Target To Save
// ~~~~~
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture::SaveAsBitmap(CString sFilePathName)
//=============================================================================
{
BOOL bResult = FALSE;
ILockBytes *Buffer = 0;
IStorage *pStorage = 0;
IStream *FileStream = 0;
BYTE *BufferBytes;
STATSTG BytesStatistics;
D OutData;
long OutStream;
CFile BitmapFile; CFileException e;
double SkipFloat = 0;
DWORD ByteSk= 0;
_ULARGE_INTEGER RealData;
CreateILockBytesOnHGlobal(NULL, TRUE, &Buffer); // Create ILockBytes Buffer
HRESULT hr = ::StgCreateDocfileOnILockBytes(Buffer,
STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage);
hr = pStorage->CreateStream(L"PICTURE",
STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, 0, &FileStream);
m_pPict->SaveAsFile(FileStream, TRUE, &OutStream); // Copy Data Stream
FileStream->Release();
pStorage->Release();
Buffer->Flush();
// Get Statistics For Final Size Of Byte Array
Buffer->Stat(&BytesStatistics, STATFLAG_NONAME);
// Cut UnNeeded Data Coming From SaveAsFile() (Leave Only "Pure" Picture Data)
SkipFloat = (double(OutStream) / 512); // Must Be In a 512 Blocks...
if(SkipFloat > DWORD(SkipFloat)) ByteSkip = (DWORD)SkipFloat + 1;
else ByteSkip = (DWORD)SkipFloat;
ByteSkip = ByteSkip * 512; // Must Be In a 512 Blocks...
// Find Difference Between The Two Values
ByteSkip = (DWORD)(BytesStatistics.cbSize.QuadPart - ByteSkip);
// Allocate Only The "Pure" Picture Data
RealData.LowPart = 0;
RealData.HighPart = 0;
RealData.QuadPart = ByteSkip;
BufferBytes = (BYTE*)malloc(OutStream);
if(BufferBytes == NULL)
{
Buffer->Release();
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, "Can not allocate enough memoryt", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
}
Buffer->ReadAt(RealData, BufferBytes, OutStream, &OutData);
if(BitmapFile.Open(sFilePathName, CFile::typeBinary | CFile::modeCreate | CFile::modeWrite, &e))
{
BitmapFile.Write(BufferBytes, OutData);
BitmapFile.Close();
bResult = TRUE;
}
else // Write File Failed...
{
TCHAR szCause[255];
e.GetErrorMessage(szCause, 255, NULL);
HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
MessageBoxEx(hWnd, szCause, ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
bResult = FALSE;
}
Buffer->Release();
free(BufferBytes);
return(bResult);
}
LONG CPicture::get_Height()
{
LONG nHeight = 0;
if (m_pPict != NULL)
{
m_pPict->get_Height(&nHeight);
}
return nHeight;
}
LONG CPicture::get_Width()
{
LONG nWidth = 0;
if (m_pPict != NULL)
{
m_pPict->get_Width(&nWidth);
}
return nWidth;
}
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-997171/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- MATLAB學習之gif圖片讀取顯示Matlab
- Java實現emf轉jpg png 圖片轉換Java
- 數字影像處理(極簡) 第三章 BMP檔案的讀取與顯示(docx)
- 第三章 載入並顯示BMP影像
- JAVA中如何獲得JPG或GIF圖片的正常顯示高度和寬度呢?Java
- bmp to jpg(32位bmp也可處理)
- 自定義bmp影像縮放及在lcd螢幕任意位置顯示
- bmp是什麼格式的檔案 怎麼把jpg轉換為bmp
- 怎麼將bmp格式圖片轉換jpg格式的
- PlY檔案讀取顯示
- qt 使用qmake pro檔案新增 ico圖示,程式執行時顯示圖示,exe也顯示圖示QT
- WSL2 Xlaunch 轉發顯示影像
- 【LaTeX入門】08、將png、bmp、jpg轉換成eps
- iftop介面顯示介紹[轉]
- BMP、GIF、JPEG、PNG、SVG、WebP區別SVGWeb
- 使用Excel的VBA來讀取和修改bmp點陣圖畫素資料Excel
- Photoshop將png轉為ico圖示
- jquery使用ajax讀取後臺資料在表格中顯示jQuery
- 讀取mysq資料庫l資料,並使用dataview顯示資料庫View
- 將bmp檔案壓縮為jpg檔案
- python使用cv2讀取影像Python
- 讓emacs完美顯示BMP檔案的辦法Mac
- BMP圖片的複製#顯示到螢幕
- 使用Hibernate和Struts向資料庫中儲存、讀取並顯示圖片資料庫
- 讀取顯示CLOB的值,不能讀取啊,請高手指點11!
- c# winform下sql圖片二進位制儲存/讀取/顯示/寫入XML/讀取XML顯示C#ORMSQLXML
- linux系統lcd顯示jpg格式圖片Linux
- 程式介面多模式顯示的實現 (轉)模式
- LCD螢幕顯示PNG影像
- Maui 讀取外部檔案顯示到Blazor中UIBlazor
- 用Qt5和OpenCV讀取顯示中文路徑的圖片QTOpenCV
- 從ARM機上讀取JPG檔案程式碼
- Nodejs學習筆記-讀取顯示圖片NodeJS筆記
- OpenCV_python全屏顯示影像OpenCVPython
- 使用ijl庫Jpg轉RGB
- 介面的實現方式(顯示和隱示)及協變和逆變
- 顯示網路介面列表
- 影像和圖示轉換工具:Snap Converter for macMac