//Picture.h
#ifndef CPICTURE_H
#define CPICTURE_H
#include <string>
#include <afxwin.h>
#include <atlbase.h>
using namespace std;
class CPicture
{
private:
string fileName;
int startX;
int startY;
int endX;
int endY;
HDC hdc;
public:
CPicture(char *fileName);
void SetStart(int x,int y);
void SetEnd(int x,int y);
void SetHDC(HDC hdc);
void Draw();
void SetFile(char *fileName);
};
#endif
//Picture.cpp
#include "CPicture.h"
CPicture::CPicture(char *fileName)
{
this->fileName = fileName;
startX = startY = 0;
endX = endY = 0;
}
void CPicture::SetStart(int x,int y)
{
startX = x;
startY = y;
}
void CPicture::SetEnd(int x,int y)
{
endX = x;
endY = y;
}
void CPicture::SetHDC(HDC hdc)
{
this->hdc = hdc;
}
void CPicture::Draw()
{
::CoInitialize(NULL); // COM 初始化
HRESULT hr;
CFile file;
file.Open( fileName.c_str(), CFile::modeRead | CFile::shareDenyNone ); // 读入文件内容
DWORD dwSize = file.GetLength();
HGLOBAL hMem = ::GlobalAlloc( GMEM_MOVEABLE, dwSize );
LPVOID lpBuf = ::GlobalLock( hMem );
file.Read( lpBuf, dwSize );
file.Close();
::GlobalUnlock( hMem );
IStream * pStream = NULL;
IPicture * pPicture = NULL;
// 由 HGLOBAL 得到 IStream,参数 TRUE 表示释放 IStream 的同时,释放内存
hr = ::CreateStreamOnHGlobal( hMem, TRUE, &pStream );
ASSERT ( SUCCEEDED(hr) );
hr = ::OleLoadPicture( pStream, dwSize, TRUE, IID_IPicture, ( LPVOID * )&pPicture );
ASSERT(hr==S_OK);
long nWidth,nHeight; // 宽高,MM_HIMETRIC 模式,单位是0.01毫米
pPicture->get_Width( &nWidth ); // 宽
pPicture->get_Height( &nHeight ); // 高
按窗口尺寸显示
pPicture->Render(hdc,startX,startY,endX,endY,
0,nHeight,nWidth,-nHeight,NULL);
if ( pPicture ) pPicture->Release();// 释放 IPicture 指针
if ( pStream ) pStream->Release(); // 释放 IStream 指针,同时释放了 hMem
::CoUninitialize();
}
void CPicture::SetFile(char *fileName)
{
this->fileName = fileName;
}