GDAL裁剪tif图(保留经纬度)
void ImageCut(const char* pszSrcFile, const char* pszDstFile, int iStartX, int iStartY, int iSizeX, int iSizeY,const char* pszFormat)
{
GDALAllRegister();
GDALDataset* pSrcDS=(GDALDataset*)GDALOpen(pszSrcFile, GA_ReadOnly);
GDALDataType eDT = pSrcDS->GetRasterBand(1)->GetRasterDataType();
int iBandCount = pSrcDS->GetRasterCount();
// 根据裁切范围确定裁切后的图像宽高
int iDstWidth = iSizeX;
int iDstHeight = iSizeY;
double adfGeoTransform[6] = {0};
pSrcDS->GetGeoTransform(adfGeoTransform);
// 计算裁切后的图像的左上角坐标
adfGeoTransform[0] = adfGeoTransform[0] + iStartX*adfGeoTransform[1] + iStartY*adfGeoTransform[2];
adfGeoTransform[3] = adfGeoTransform[3] + iStartX*adfGeoTransform[4] + iStartY*adfGeoTransform[5];
// 创建输出文件并设置空间参考和坐标信息
GDALDriver* poDriver = (GDALDriver *)GDALGetDriverByName(pszFormat);
GDALDataset *pDstDS = poDriver->Create(pszDstFile, iDstWidth, iDstHeight, iBandCount, eDT, NULL);
pDstDS->SetGeoTransform(adfGeoTransform);
pDstDS->SetProjection(pSrcDS->GetProjectionRef());
int *pBandMap = new int[iBandCount];
for (int i=0; i<iBandCount; i++)
pBandMap[i] = i+1;
// 下面这里需要根据数据类型来判断,申请不同类型的缓存来进行处理,这里仅仅以8bit图像进行演示
if (eDT == GDT_Byte) // 如果是8bit图像
{
// 申请所有数据所需要的缓存,如果图像太大应该用分块处理
char *pDataBuff = new char[iDstWidth*iDstHeight*iBandCount];
pSrcDS->RasterIO(GF_Read, iStartX, iStartY, iSizeX, iSizeY, pDataBuff, iSizeX, iSizeY, eDT, iBandCount, pBandMap, 0, 0, 0);
pDstDS->RasterIO(GF_Write, 0, 0, iSizeX, iSizeY, pDataBuff, iSizeX, iSizeY, eDT, iBandCount, pBandMap, 0, 0, 0);
delete(pDataBuff);
}
else
{
// 其他类型的图像,与8bit类似,就是申请的缓存类型不同而已
}
delete(pBandMap);
GDALClose((GDALDatasetH)pSrcDS);
GDALClose((GDALDatasetH)pDstDS);
return ;
}
函数调用时参数pszFormat
tif图片:GTiff
转载自:https://blog.csdn.net/grllery/article/details/77815059