MFC中怎样读取一个JPG文件或BMP位图文件
2016-12-16
展开全部
在MFC中如何读取并显示jpg文件
//picture.h
#pragma once
#include <atlbase.h>
class CPicture {
public:
CPicture();
~CPicture();
// Load frm various sosurces
BOOL Load(LPCTSTR pszPathName);
BOOL Render(CDC* pDC, CRect rc=CRect(0,0,0,0),
LPCRECT prcMFBounds=NULL) const;
CSize GetImageSize(CDC* pDC=NULL) const;
operator IPicture*() { return m_spIPicture; }
void GetHIMETRICSize(OLE_XSIZE_HIMETRIC& cx, OLE_YSIZE_HIMETRIC& cy) const {
cx = cy = 0;
const_cast<CPicture*>(this)->m_hr = m_spIPicture->get_Width(&cx);
ASSERT(SUCCEEDED(m_hr));
const_cast<CPicture*>(this)->m_hr = m_spIPicture->get_Height(&cy);
ASSERT(SUCCEEDED(m_hr));
}
void Free() {
if (m_spIPicture) { m_spIPicture.Release();}
}
//picture.cpp
#include "stdafx.h"
#include "Picture.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CPicture::CPicture()
{}
CPicture::~CPicture()
{}
BOOL CPicture::Load(LPCTSTR pszPathName)
{
CFile file;
if (!file.Open(pszPathName,CFile::modeRead|CFile::shareDenyWrite))
return FALSE;
BOOL bRet = Load(file);
file.Close();
return bRet;
}
BOOL CPicture::Render(CDC* pDC, CRect rc, LPCRECT prcMFBounds) const
{
ASSERT(pDC);
if (rc.IsRectNull()) {
CSize sz = GetImageSize(pDC);
rc.right = sz.cx;
rc.bottom = sz.cy;
}
long hmWidth,hmHeight; // HIMETRIC units
GetHIMETRICSize(hmWidth, hmHeight);
m_spIPicture->Render(*pDC, rc.left, rc.top, rc.Width(), rc.Height(),
0, hmHeight, hmWidth, -hmHeight, prcMFBounds);
return TRUE;
}
CSize CPicture::GetImageSize(CDC* pDC) const
{
if (!m_spIPicture)
return CSize(0,0);
LONG hmWidth, hmHeight; // HIMETRIC units
m_spIPicture->get_Width(&hmWidth);
m_spIPicture->get_Height(&hmHeight);
CSize sz(hmWidth,hmHeight);
if (pDC==NULL) {
CWindowDC dc(NULL);
dc.HIMETRICtoDP(&sz); // convert to pixels
} else {
pDC->HIMETRICtoDP(&sz);
}
return sz;
}
//最后在CView类的OnDraw方法中加入调用:
void CShowImageView::OnDraw(CDC* pDC)
{
CShowImageDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
CPicture* ppic = new CPicture();
std::string filename("C:\\mypic.jpg");
int slength = (int)filename.length() + 1;
int len = MultiByteToWideChar(CP_ACP, 0, filename.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, filename.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
ppic->Load(r.c_str());
ASSERT(ppic);
if (*ppic) {
CRect rc(0,0,500,500);
ppic->Render(pDC,rc);
}
}
protected:
CComQIPtr<IPicture>m_spIPicture;
// ATL smart pointer to IPicture
HRESULT m_hr; // last error code
};
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询