How to use GDALWarp in C++
GDALWarp
is a powerful function in the GDAL (Geospatial Data Abstraction Library) library used for image reprojection and warping. To use GDALWarp
in C++, you need to follow these steps:
GDALWarp
function to perform the reprojection/warping.Here is a basic example demonstrating how to use GDALWarp
in C++:
#include "gdal_priv.h"
#include "cpl_conv.h" // for CPLMalloc()
#include "gdalwarper.h"
int main()
{
// Initialize GDAL
GDALAllRegister();
// Open the source dataset
const char* srcFilename = "source.tif";
GDALDataset* srcDataset = (GDALDataset*)GDALOpen(srcFilename, GA_ReadOnly);
if (srcDataset == nullptr)
{
printf("Failed to open source dataset.\n");
return 1;
}
// Define the output projection (WGS84 in this example)
const char* dstProjection = "EPSG:4326";
// Create the destination dataset
const char* dstFilename = "warped.tif";
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
if (driver == nullptr)
{
printf("GTiff driver not available.\n");
GDALClose(srcDataset);
return 1;
}
// Create a copy of the source dataset with the new projection
GDALDataset* dstDataset = driver->CreateCopy(dstFilename, srcDataset, FALSE, nullptr, nullptr, nullptr);
if (dstDataset == nullptr)
{
printf("Failed to create destination dataset.\n");
GDALClose(srcDataset);
return 1;
}
// Set the projection for the destination dataset
dstDataset->SetProjection(dstProjection);
// Set up the warp options
GDALWarpOptions* warpOptions = GDALCreateWarpOptions();
warpOptions->hSrcDS = srcDataset;
warpOptions->hDstDS = dstDataset;
warpOptions->nBandCount = 1;
warpOptions->panSrcBands = (int*)CPLMalloc(sizeof(int) * warpOptions->nBandCount);
warpOptions->panDstBands = (int*)CPLMalloc(sizeof(int) * warpOptions->nBandCount);
warpOptions->panSrcBands[0] = 1;
warpOptions->panDstBands[0] = 1;
// Create the warp operation
GDALWarpOperation warpOperation;
warpOperation.Initialize(warpOptions);
// Perform the warp
CPLErr err = warpOperation.WarpRegion(0, 0, dstDataset->GetRasterXSize(), dstDataset->GetRasterYSize());
if (err != CE_None)
{
printf("Warp operation failed.\n");
}
// Clean up
GDALDestroyWarpOptions(warpOptions);
GDALClose(srcDataset);
GDALClose(dstDataset);
return 0;
}
GDALAllRegister()
initializes all GDAL drivers.GDALOpen()
opens the source dataset.CreateCopy()
creates a copy of the source dataset with the new projection.SetProjection()
sets the projection for the destination dataset.GDALCreateWarpOptions()
creates warp options, and you set the source and destination datasets and bands.GDALWarpOperation
is used to perform the warp.GDALDestroyWarpOptions()
and GDALClose()
clean up resources.Make sure you have GDAL installed and properly configured in your development environment to compile and run this