/**
* 通用新增为tif上色 现在tiff不上色
*
* @param tifUrl 文件地址
* @return levels索引位置对应生成的文件地址
*/
public String tiffProcess(String tifUrl) {
Dataset open = gdal.Open(tifUrl, gdalconstConstants.GA_ReadOnly);
/*
获取gtiff 数据
*/
//行数 高
int iYSize = open.getRasterYSize();
//列数 宽
int iXSize = open.getRasterXSize();
//仿射矩阵
double[] doubles = open.GetGeoTransform();
//地图投影信息
String projection = open.GetProjection();
//将数据写成数组
Band sourceBand = open.GetRasterBand(1);
double[] doubles1 = new double[2];
sourceBand.ComputeRasterMinMax(doubles1);
double[][] data = new double[iYSize][iXSize];
for (int i = 0; i < iYSize; i++) {
double[] d1 = new double[iXSize];
sourceBand.ReadRaster(0, i, iXSize, 1, d1); //读取一行数据
for (int i1 = 0; i1 < d1.length; i1++) {
if (d1[i1] > 0) {
data[i][i1] = d1[i1];
}
}
}
/*
生成tiff
*/
Driver driver = gdal.GetDriverByName("GTiff");
String newFile = tifUrl.substring(0, tifUrl.length() - 4) + ".tif";
Dataset create = driver.Create(newFile, iXSize, iYSize, 1, gdalconst.GDT_Byte);
//设置仿射矩阵
create.SetGeoTransform(doubles);
//设置投影信息
create.SetProjection(projection);
//设置波段
Band targetBand = create.GetRasterBand(1);
double[] colorRange = new double[2];
sourceBand.ComputeRasterMinMax(colorRange);
targetBand.SetNoDataValue(0);
//设置波段值
int[] temp = new int[1];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
temp[0] = convertPixel(colorRange[0], colorRange[1], data[i][j]);
if (temp[0] != 0) {
targetBand.WriteRaster(j, i, 1, 1, temp);
}
}
}
open.delete();
create.delete();
return newFile;
}
/**
* 像素波段等级区间判断转换 1-4 高-低
*
* @param min 像素最小值
* @param max 像素最大值
* @param now 比较值
*/
public static int convertPixel(double min, double max, double now) {
//因波段值存在小数不好计算 这里默认相乘 可以根据实际业务定义
min = 100000D * min;
max = max * 100000D;
now = now * 100000D;
double v = (max - min) / 4;
double v2 = v * 2;
double v3 = v * 3;
if (min <= now && (min + v) > now) {//高
return 1;
} else if ((min + v) <= now && (min + v2) > now) {//较高
return 2;
} else if ((min + v2) <= now && (min + v3) > now) { //中
return 3;
} else if ((min + v3) <= now && max >= now) { //低
return 4;
} else {
return 0;
}
}
java通过gdal解析单波段tiff并根据业务生成新的tiff文件
最新推荐文章于 2024-07-29 23:52:31 发布