| | |
| | | package com.se.simu.utils; |
| | | |
| | | import org.apache.commons.imaging.*; |
| | | import org.gdal.gdal.Band; |
| | | import org.gdal.gdal.Dataset; |
| | | import org.gdal.gdal.gdal; |
| | | import org.gdal.gdalconst.gdalconstConstants; |
| | | |
| | | import javax.imageio.ImageIO; |
| | | import java.awt.*; |
| | |
| | | import java.io.IOException; |
| | | |
| | | public class TiffToRGBUtil { |
| | | public static void tifToPng(String tifPath, String pngPath) throws Exception { |
| | | // 注册所有的 GDAL 驱动 |
| | | gdal.AllRegister(); |
| | | // 输入的 TIFF 文件路径 |
| | | // 打开输入的 TIFF 数据集 |
| | | Dataset dataset = gdal.Open(tifPath, gdalconstConstants.GA_ReadOnly); |
| | | if (dataset == null) { |
| | | System.err.println("无法打开输入的 TIFF 文件"); |
| | | return; |
| | | } |
| | | // 获取地理变换信息 |
| | | double[] geoTransform = dataset.GetGeoTransform(); |
| | | // 获取第一个波段 |
| | | Band band = dataset.GetRasterBand(1); |
| | | // 获取图像宽度和高度 |
| | | int width = dataset.getRasterXSize(); |
| | | int height = dataset.getRasterYSize(); |
| | | // 读取图像数据到字节数组 |
| | | byte[] imageData = new byte[width * height]; |
| | | band.ReadRaster(0, 0, width, height, imageData); |
| | | BufferedImage pngImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); |
| | | // 假设高度信息存储在灰度值中,根据地理变换信息和像素值计算实际高度 |
| | | for (int y = 0; y < height; y++) { |
| | | for (int x = 0; x < width; x++) { |
| | | int pixelValue = imageData[y * width + x] & 0xFF; |
| | | // 假设高度信息存储在像素值中 |
| | | double pixelHeight = pixelValue * geoTransform[5]; |
| | | //height = -10000 + ((R * 256 * 256 + G * 256 + B) * 0.1) |
| | | int value = (int) (pixelHeight + 10000) * 10; |
| | | //value=(R * 256 * 256 + G * 256 + B); |
| | | int r = value / (256 * 256); |
| | | value = value % (256 * 256); |
| | | int g = value / 256; |
| | | int b = value % 256; |
| | | Color color = new Color(r, g, b); |
| | | System.out.printf("Pixel (%d, %d): R=%d, G=%d, B=%d%n", x, y, r, g, b); |
| | | int newRgb = color.getRGB(); |
| | | // 将处理后的像素颜色值设置到新的 PNG 图像中 |
| | | pngImage.setRGB(x, y, newRgb); |
| | | } |
| | | } |
| | | // 保存为 PNG 图像 |
| | | ImageIO.write(pngImage, "png", new File(pngPath)); |
| | | // 释放资源 |
| | | dataset.delete(); |
| | | } |
| | | |
| | | public static void tiffToPng(String tifPath, String pngPath) throws Exception { |
| | | // 输出的 PNG 文件路径 |
| | |
| | | System.out.println(heightValue); |
| | | // 简单地将红色分量根据高度值进行调整,例如,越高越红 |
| | | // 确保红色分量不超过 255 |
| | | //red = Math.min((int) (red + (heightValue * 0.5)), 255); |
| | | red = Math.min(red, 255); |
| | | green = Math.min(green, 255); |
| | | blue = Math.min(blue, 255); |
| | | // 重新组合 ARGB 值 |
| | | Color color = new Color(red, green, blue); |
| | | System.out.printf("Pixel (%d, %d): R=%d, G=%d, B=%d%n", x, y, red, green, blue); |