作者:朱金灿
来源:http://blog.csdn.net/clever101
使用gdal创建一个100*100的红色的geotiff图像,代码如下:
#include <assert.h> #include <string> #include <gdal.h> #include <gdal_priv.h> #include <gdalwarper.h> int _tmain(int argc, _TCHAR* argv[]) { // 用于支持中文路径 CPLSetConfigOption(_T("GDAL_FILENAME_IS_UTF8"),_T("NO")); GDALAllRegister(); GDALDriver* pDriver = GetGDALDriverManager()->GetDriverByName(_T("GTiff")); if(NULL!=pDriver) { // 创建的geotif文件路径 std::string strFileFullPath = "D:\1.tif"; // 下面是默认选项 char** papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "INTERLEAVE", "BAND" ); //bsq int nImgWidth = 100; // 图像宽度 int nImgHeight = 100; // 图像高度 //创建位浮点数的geotif图像 GDALDataset* pCreateDataset = pDriver->Create(strFileFullPath.c_str(),nImgWidth,nImgHeight,3,GDT_Byte,papszOptions); if(pCreateDataset != NULL) { // 定义仿射变换参数 double dblGeoTransform[6] = {0}; /* dblGeoTransform[0] --- 图像左上角的横坐标 dblGeoTransform[1] --- 单个像元宽度,使用图像x轴范围/图像宽度得到 dblGeoTransform[2] --- 0.0 dblGeoTransform[3] --- 图像左上角的纵坐标 dblGeoTransform[4] --- 0.0 dblGeoTransform[5] --- 单个像元高度,使用图像y轴范围/图像高度得到 */ dblGeoTransform[0] = 116.0; // 东经度 dblGeoTransform[1] = (120.0-116.0)/static_cast<double>(nImgWidth); // 图像的地理范围为东经度到东经度 dblGeoTransform[3] = 39.0; // 北纬度 dblGeoTransform[5] = (37.0-39.0)/static_cast<double>(nImgHeight);// 图像的地理范围为北纬度到北纬度 CPLErr err = CE_None; if(CE_None == pCreateDataset->SetGeoTransform(dblGeoTransform)) { // 设置经纬度坐标 std::string strWkt = "GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]]"; if(CE_None == pCreateDataset->SetProjection(strWkt.c_str())) { GDALRasterBand* poBand = NULL; poBand = pCreateDataset->GetRasterBand(1); unsigned char* pcBuffer = new unsigned char[nImgWidth*nImgHeight]; memset(pcBuffer,255,nImgWidth*nImgHeight*sizeof(unsigned char)); assert(NULL!=poBand); // 将第一波段的值全部设为.0 err = poBand->RasterIO(GF_Write,0,0,nImgWidth,nImgHeight,pcBuffer,nImgWidth,nImgHeight,GDT_Byte,0,0); // GF_Read } } GDALClose(pCreateDataset); } } GDALDestroyDriverManager(); getchar(); return 0; }
用ENVI ZOOM打开时居然是全黑,如下图:
开始百思不得其解,后来大致明白了,ENVI初始显示是作了2%线性拉伸的,就是对图像DN值分布在2%和98%之间的做线性拉伸,由于所有波段的最大值和最小值都一样,没有拉伸空间,那么就是保留初始化值0,所以就显示为0。
就是如果不进行拉伸的话,是可以正确显示的,如下图:
参考: