gdal读取图像数据,构建gdi+显示
将GDALOpen打开的文件用GDI+绘画出来
基于MFC单文档(XXXXView类的基类选择CScrollView)
CTestView.h
{
#include "gdal_priv.h"
...
GDALDataset* m_pDataset;
CSize sizeTotal; //设置滚动条
CString picturePath; //图片的位置
BOOL test; //文件是否打开
ULONG_PTR m_gdiplusToken;
..
}
TestView.cpp中
…
#include <gdiplus.h>
…
CTestView::TestView()
{
// TODO: 在此处添加构造代码
test=FALSE;
//...
}
CTestView::~CTestView()
{
// 释放GDI+资源
Gdiplus::GdiplusShutdown( m_gdiplusToken );
}
void CTestView::OnFileOpen()
{
// TODO: 在此添加命令处理程序代码
TCHAR szFilter[] = _T("TIF(*.tif)|*.tif|image file(*.bmp;*.jpg)|*.bmp;*.jpg|All Files(*.*)|*.*|");
CFileDialog fileDlg(TRUE,NULL, NULL, 0, szFilter, this);
fileDlg.m_ofn.lpstrTitle=_T("OPEN IMAGE");
if (fileDlg.DoModal()==IDOK)
{
picturePath=fileDlg.GetPathName();
GDALAllRegister();
std::string luj=CStringA(picturePath);
m_pDataset =(GDALDataset*) GDALOpen(luj.c_str(),GA_ReadOnly );
if(m_pDataset==NULL )
{
AfxMessageBox(_T("文件打开失败!!!"));
return;
}
test=TRUE;
Invalidate();
}
}
void CTestView::OnDraw(CDC* pDC)
{
TestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
if(test)
{
// 初始化GDI+
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup( &m_gdiplusToken, &gdiplusStartupInput, NULL );
int dataWidth=m_pDataset->GetRasterXSize();
int dataHeight=m_pDataset->GetRasterYSize();
int dataBands = m_pDataset->GetRasterCount();
//设置滚动条
sizeTotal.cx=m_pDataset->GetRasterXSize();
sizeTotal.cy=m_pDataset->GetRasterYSize();
SetScrollSizes(MM_TEXT,sizeTotal);
BYTE* pBuffer = new BYTE[dataWidth*dataHeight*dataBands];
Gdiplus::Bitmap* m_pBitmap=NULL;
if (dataBands==1) //8位灰度图
{
int band_list[1]={1} ;
CPLErr err = m_pDataset->RasterIO(GF_Read, 0, 0, dataWidth, dataHeight, pBuffer, dataWidth, dataHeight,
GDT_Byte,dataBands,NULL,1,dataWidth,1);
m_pBitmap=::new Gdiplus::Bitmap(dataWidth, dataHeight,dataWidth*dataBands,
PixelFormat8bppIndexed, (BYTE*)pBuffer);
Gdiplus::ColorPalette *pal=(Gdiplus::ColorPalette *)malloc(sizeof(Gdiplus::ColorPalette)+256*sizeof(Gdiplus::ARGB));
pal->Count=256;
pal->Flags=0;
for (int i=0;i<256;i++)
{
pal->Entries[i]=Gdiplus::Color::MakeARGB(255,i,i,i);
}
m_pBitmap->SetPalette(pal);
free(pal);
}
else if(dataBands==3) //24位RGB图
{
int band_list[3] = {3,2,1};
CPLErr err = m_pDataset->RasterIO(GF_Read, 0, 0, dataWidth, dataHeight, pBuffer, dataWidth, dataHeight,
GDT_Byte,dataBands,band_list,3,dataWidth*3, 1);
m_pBitmap=::new Gdiplus::Bitmap(dataWidth, dataHeight, dataWidth*dataBands,
PixelFormat24bppRGB, (BYTE*)pBuffer);
}
Gdiplus::Graphics graphics(pDC->GetSafeHdc());
graphics.DrawImage(m_pBitmap, 0, 0,dataWidth,dataHeight);
delete pBuffer;
ReleaseDC(pDC);
}
}
转载自:https://blog.csdn.net/grllery/article/details/77898580