GDAL保存图像文件

所有支持创建的格式驱动都支持CreateCopy()函数,但是并不一定支持Create()函数,为了确定数据格
式是否支持Create或CreateCopy,可以检查驱动对象中的DCAP_CREATE和DCAP_CREATECOPY元数据。

poDriver = GetGDALDriverManager()->GetDriverByName("Gtiff"); papszMetadata = https://www.it610.com/article/poDriver->GetMetadata(); if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) ) printf( "Driver %s supports Create() method.\n", pszFormat ); if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATECOPY, FALSE ) ) printf( "Driver %s supports CreateCopy() method.\n", pszFormat );




//从文件名获取文件格式
char* CtemplatematchingDoc::findImageTypeGDAL(char *pDstImgFileName)
{
char *dstExtension = strlwr(strrchr(pDstImgFileName,'.') + 1);
char *Gtype = NULL;
if(0 == strcmp(dstExtension,"bmp")) Gtype = "BMP";
else if (0 == strcmp(dstExtension,"jpg")) Gtype = "JPEG";
else if (0 == strcmp(dstExtension,"png")) Gtype = "PNG";
else if (0 == strcmp(dstExtension,"tif")) Gtype = "GTiff";
else if (0 == strcmp(dstExtension,"gif")) Gtype = "GIF";
else Gtype = NULL;

return Gtype;
}

//使用Create保存图像
bool CtemplatematchingDoc::WriteImageGDAL(char* pDstImgFileName, uint8_t **pImageData,int width,int height,int nChannels)
{
assert ( !(pDstImgFileName == NULL || pImageData =https://www.it610.com/article/= NULL || width <1 || height < 1 || nChannels < 1));

GDALAllRegister();
char *GType = NULL;
GType = findImageTypeGDAL(pDstImgFileName);
if (GType == NULL){ return false; }

GDALDriver *pMemDriver = NULL;
pMemDriver = GetGDALDriverManager()->GetDriverByName(GType);
if( pMemDriver == NULL ) { return false; }

//使用Creat方式保存图像,需要设置各种参数并填充栅格数据
GDALDataset * pMemDataSet =
pMemDriver->Create(pDstImgFileName,width,height,nChannels,GDT_Byte,NULL);
GDALRasterBand *pBand = NULL;
int nLineCount = width * nChannels;
for (int i = 1; i <= nChannels; i++)
{
pBand = pMemDataSet->GetRasterBand(nChannels-i+1);
pBand->RasterIO(GF_Write,
0,
0,
width,
height,
pImageData[i-1],
width,
height,
GDT_Byte,
0,
0);
}
GDALClose(pMemDataSet);
return true;
}


//使用CreateCopy方式直接从已有数据集中复制图像
GDALDriver *pDstDriver = NULL;
pDstDriver = (GDALDriver *)GDALGetDriverByName(GType);
if (pDstDriver == NULL) { return false; }
pDstDriver->CreateCopy(pDstImgFileName,pMemDataSet,FALSE, NULL, NULL, NULL);


复制projection 以及Geo信息
//CopyProjection
pOutputDataset->SetProjection(pIODataset->GetProjectionRef());

//CopyGEO
double dGeoTrans[6] = {0};
pIODataset->GetGeoTransform(dGeoTrans);
pOutputDataset->SetGeoTransform(dGeoTrans);


pImageData[bands][height*width]中:
pImageData[0]中存储的是B波段数据
pImageData[1]中存储的是G波段数据
pImageData[2]中存储的是R波段数据

用GDAL存储图像时的顺序为BGR(一般彩色图像都是以BGR存储),但读取图像的顺序为RGB。

【GDAL保存图像文件】

    推荐阅读