利用GDAL库读取GeoTIFF文件

    经过一天的学习,终于对gdal库有所了解,下面是利用GDAL读取TIFF文件程序。

void CTestView::OnFileOpen()
{
     // TODO: Add your command handler code here

     char  szFilter[] = "GeoTiff (*.tif)|*.tif|All Files (*.*)|*.*||";
     CString filePath("");
     CFileDialog fileOpenDlg(TRUE, "tif", NULL,OFN_HIDEREADONLY,szFilter);
     if (fileOpenDlg.DoModal() == IDOK)
     {
          VERIFY(filePath = fileOpenDlg.GetPathName());
     }
 
     CString strFilePath(filePath);
     GDALDataset *poDataset;   //GDAL数据集
     GDALAllRegister();
     poDataset = (GDALDataset *) GDALOpen(strFilePath, GA_ReadOnly );
     if( poDataset == NULL )
     {
         AfxMessageBox("文件打开失败!!!");
         return;
     } 

    GDALRasterBand *poBand1;   //遥感的一个波段
    GDALRasterBand *poBand2;
    GDALRasterBand *poBand3;
    int nBandCount;
    nBandCount=poDataset->GetRasterCount();
    poBand1=poDataset->GetRasterBand(1);
    poBand2=poDataset->GetRasterBand(2);
    poBand3=poDataset->GetRasterBand(3);

   //获取图像的尺寸
   //获取图像窗口尺寸
   CRect rect;
   GetClientRect(rect);

   int nImgSizeX=poDataset->GetRasterXSize();
   int nImgSizeY=poDataset->GetRasterYSize();
   int nBufferSizeX,nBufferSizeY;
   nBufferSizeY=rect.Height();
   float m_fXYRation;
   m_fXYRation = (float)nImgSizeY/(float)nImgSizeX;
   nBufferSizeX = (int)(m_fXYRation*(float)nBufferSizeY); 

   BYTE *pafScanblock1;
   BYTE *pafScanblock2;
   BYTE *pafScanblock3;
   pafScanblock1 = (BYTE *) CPLMalloc(sizeof(BYTE)*(nBufferSizeX)*(nBufferSizeY));
   pafScanblock2 = (BYTE *) CPLMalloc(sizeof(BYTE)*(nBufferSizeX)*(nBufferSizeY));
   pafScanblock3 = (BYTE *) CPLMalloc(sizeof(BYTE)*(nBufferSizeX)*(nBufferSizeY));
   poBand1->RasterIO( GF_Read, 0, 0,nBufferSizeX,nBufferSizeY,
   pafScanblock1,nBufferSizeX,nBufferSizeY, GDT_Byte,0, 0 );
   poBand2->RasterIO( GF_Read, 0, 0,nBufferSizeX,nBufferSizeY,
   pafScanblock2,nBufferSizeX,nBufferSizeY, GDT_Byte,0, 0 );
   poBand3->RasterIO( GF_Read, 0, 0,nBufferSizeX,nBufferSizeY,
   pafScanblock3,nBufferSizeX,nBufferSizeY, GDT_Byte,0, 0 );

   //在View逐点显示图像
   for (int i=0;i   for (int j=0;j  {
       BYTE dn1=*pafScanblock1;
       BYTE dn2=*pafScanblock2;
       BYTE dn3=*pafScanblock3;
       CClientDC dc(this);
       dc.SetPixel(j,i,RGB(dn1,dn2,dn3));

       pafScanblock1++;
       pafScanblock2++;
      pafScanblock3++;
  }

}

你可能感兴趣的:(C++/VC)