using OSGeo.GDAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Resample1
{
class Program
{
static void Main(string[] args)
{
string srcFileName = @"E:\GDAL\GDALPractice\GDAL_in_CSharp\chapter07\QQ20150414101043.tif";
string dstFileName = @"E:\GDAL\GDALPractice\GDAL_in_CSharp\chapter07\result_resample1.tif";
double xRatio = 0;
double yRatio=0;
bool b = false;
while (b==false)
{
try
{
//xRatio、yRatio大于1则图像变大,小于1则变小
Console.WriteLine("输入X方向的采样比例:");
xRatio = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("输入Y方向的采样比例:");
yRatio = Convert.ToDouble(Console.ReadLine());
b = true;
}
catch
{
Console.WriteLine("输入错误,请重新输入:");
}
}
Gdal.AllRegister();
Dataset srcDs = Gdal.Open(srcFileName, Access.GA_ReadOnly);
Driver srcDrv=srcDs.GetDriver();
Band srcBand = srcDs.GetRasterBand(1);
DataType type = srcBand.DataType;
int bandCount = srcDs.RasterCount;
int iWidth = srcDs.RasterXSize;
int iHeight = srcDs.RasterYSize;
//根据采样比例计算重采样后的图像宽高
int dstImgWidth = (int)(iWidth * xRatio + 0.5);
int dstImgHeight = (int)(iHeight * yRatio + 0.5);
double[] adfGeoTransform = new double[6];
srcDs.GetGeoTransform(adfGeoTransform);
//计算重采样后的图像分辨率
adfGeoTransform[1] /= xRatio;
adfGeoTransform[5] /= yRatio;
//创建输出文件
Driver dstDrv = Gdal.GetDriverByName("GTIFF");
Dataset dstDs = dstDrv.Create(dstFileName, dstImgWidth, dstImgHeight, bandCount, DataType.GDT_Byte, null);
dstDs.SetGeoTransform(adfGeoTransform);
int[] bandNum = new int[bandCount];
for(int i=0;i<bandCount;++i)
{
bandNum[i] = i + 1;
}
if(type==DataType.GDT_Byte)
{
byte[] dstArray = new byte[bandCount * dstImgHeight * dstImgWidth];
srcDs.ReadRaster(0, 0, iWidth, iHeight, dstArray, dstImgWidth, dstImgHeight, bandCount, bandNum, 0, 0, 0);
dstDs.WriteRaster(0, 0, dstImgWidth, dstImgHeight, dstArray, dstImgWidth, dstImgHeight, bandCount, bandNum, 0, 0, 0);
}
dstDs.FlushCache();
dstDs.Dispose();
Console.WriteLine("Success");
Console.ReadLine();
}
}
}
原图:
效果: