Java集成gdal 处理解析tiff和shp数据

news2024/9/21 2:10:50

1. 配置 gdal

1.1. 官网下载

 这个是因为你电脑是 win64 位才选择哦~

下载这个,然后解压

1.2. 复制这个压缩包下的 ddl 文件

可以按照类型复制,然后复制到你的 java jDK 文件夹下

1.3. 找到你的 java jdk 文件夹

不知道 java 的文件夹位置,可以通过这个查找

 

1.4. 复制对象

将这个复制到这个1.5. 选择 release-1930-x64-gdal-3-8-5-mapserver-8-0-1\bin\gdal\java

也复制到 java/bin java/jre/java,并且放入项目里面

2. 解析 tif

package org.example.flink_springboot.geop;
 
import org.gdal.gdal.Band;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.Driver;
import org.gdal.gdal.gdal;
import org.gdal.gdalconst.gdalconst;
import org.gdal.gdalconst.gdalconstConstants;
 
public class GDALTest {
	public static void main(String[] args) {
		// 注册文件格式
		gdal.AllRegister();
		// 使用只读的方式打开图像
		Dataset poDataset = gdal.Open("F:\\learn\\flink_springboot\\src\\main\\resources\\srtm_60_05.tif", gdalconst.GA_ReadOnly);
		if (poDataset == null) {
			System.out.println("The image could not be read.");
		} else {
			// 图像打开成功
			System.out.println("The image could be read.");
			
			Driver hDriver = poDataset.GetDriver();
			// 输出文件的格式
			System.out.println("文件格式:" + hDriver.GetDescription());
			//System.out.println("文件格式:" + hDriver.getShortName() + "/" + hDriver.getLongName());
			// 输出图像的大小和波段个数
			System.out.println("size is:x:" + poDataset.getRasterXSize() + " ,y:" + poDataset.getRasterYSize()
					+ " ,band size:" + poDataset.getRasterCount());
			// 输出图像的投影信息
			if (poDataset.GetProjectionRef() != null) {
				System.out.println("Projection is " + poDataset.GetProjectionRef());
			}
			// 输出图像的坐标和分辨率信息
			double[] adfGeoTransform = new double[6];
			poDataset.GetGeoTransform(adfGeoTransform);
			System.out.println("origin : " + adfGeoTransform[0] + "," + adfGeoTransform[3]);
			System.out.println("pixel size:" + adfGeoTransform[1] + "," + adfGeoTransform[5]);
 
			
			// 分别输出各个波段的块大小,并获取该波段的最大值和最小值,颜色表信息
			for (int band = 0; band < poDataset.getRasterCount(); band++) {
				Band poBand = poDataset.GetRasterBand(band + 1);
				System.out.println("Band" + (band + 1) + ":" + "size:x:" + poBand.getXSize() + ",y:" + poBand.getYSize());
				Double[] min = new Double[1];
				Double[] max = new Double[1];
				poBand.GetMinimum(min);
				poBand.GetMaximum(max);
				if (min[0] != null || max[0] != null) {
					System.out.println("Min=" + min[0] + ",max=" + max[0]);
				} else {
					System.out.println("No Min/Max values stored in raster.");
				}
				if (poBand.GetColorTable() != null) {
					System.out.println("band" + band + "has a color table with"
							+ poBand.GetRasterColorTable().GetCount() + "entries.");
				}
				
				int buf[] = new int[poDataset.getRasterXSize()];
				for (int i = 0; i < 3; i++) {
					poBand.ReadRaster(0, i, poDataset.getRasterXSize(), 1, buf);
					for (int j = 0; j < 3; j++)
						System.out.print(buf[j] + ", ");
					System.out.println("\n");
				}
			}
 
			
			
	
 
 
			poDataset.delete();
			
			
		}
	}
}
 

3. 解析 shp

package org.example.flink_springboot.shape;
 
import org.gdal.gdal.gdal;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
 
import java.util.HashMap;
import java.util.Map;
 
public class GdalDemo_shp1 {
    public void opeanShp(String strVectorFile ) {
 
// 注册所有的驱动
        ogr.RegisterAll();
// 为了支持中文路径,请添加下面这句代码
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
// 为了使属性表字段支持中文,请添加下面这句
        gdal.SetConfigOption("SHAPE_ENCODING", "CP936");
// 读取数据,这里以ESRI的shp文件为例
        String strDriverName = "ESRI Shapefile";
// 创建一个文件,根据strDriverName扩展名自动判断驱动类型
 
        org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
 
        if (oDriver == null) {
            System.out.println(strDriverName + " 驱动不可用!\n");
            return;
        }
        DataSource dataSource = oDriver.Open(strVectorFile);
        //Layer layer = dataSource.GetLayer("test");
        Layer layer = dataSource.GetLayer(0);
 
        for(int i = 0;i<dataSource.GetLayerCount();i++) {
            Layer layerIdx = dataSource.GetLayer(i);
            System.out.println("图层名称:<==>" + layerIdx.GetName());
        }
 
        String layerName = layer.GetName();
        System.out.println("图层名称:" + layerName);
        SpatialReference spatialReference = layer.GetSpatialRef();
//System.out.println(spatialReference);
        System.out.println("空间参考坐标系:" + spatialReference.GetAttrValue("AUTHORITY", 0)
                + spatialReference.GetAttrValue("AUTHORITY", 1));
 
        double[] layerExtent = layer.GetExtent();
 
        System.out.println("图层范围:minx:" + layerExtent[0] + ",maxx:" + layerExtent[1] + ",miny:" + layerExtent[2] + ",maxy:" + layerExtent[3]);
 
 
        FeatureDefn featureDefn = layer.GetLayerDefn();
 
        int fieldCount = featureDefn.GetFieldCount();
 
        Map<String,String> fieldMap = new HashMap<String,String>();
        for (int i = 0; i < fieldCount; i++) {
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
            // 得到属性字段类型
            int fieldType = fieldDefn.GetFieldType();
            String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType);
            // 得到属性字段名称
            String fieldName = fieldDefn.GetName();
            fieldMap.put(fieldTypeName, fieldName);
        }
        System.out.println();
        System.out.println("fileMap:");
        System.out.println(fieldMap);
 
        System.out.println(layer.GetFeature(1).GetGeometryRef().ExportToJson());
        System.out.println(layer.GetFeature(2).GetGeometryRef().ExportToJson());
        System.out.println(layer.GetFeature(3).GetGeometryRef().ExportToJson());
 
        for (int i = 0; i < 12; i++) {
            Feature feature = layer.GetFeature(i);
            Object[] arr = fieldMap.values().toArray();
            for (int k = 0; k < arr.length; k++) {
                String fvalue = feature.GetFieldAsString(arr[k].toString());
                System.out.println(" 属性名称:" + arr[k].toString() + ",属性值:" + fvalue);
            }
        }
    }
 
    public static void main(String[] args) {
        GdalDemo_shp shp = new  GdalDemo_shp();
        String strVectorFile ="F:\\learn\\flink_springboot\\src\\main\\resources\\中华人民共和国.shp";
        String info = shp.opeanShp(strVectorFile);
        System.out.println(info);
    }
}
package org.example.flink_springboot.shape;
 
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
 
public class SHP {
    /**
     * 生成shape文件
     *
     * @param shpPath  生成shape文件路径(包含文件名称) filepath
     * @param encode   编码 code
     * @param geoType  图幅类型,Point和Rolygon
     * @param shpKey   data中图幅的key  geomfiled
     * @param attrKeys 属性key集合 keylist
     * @param data     图幅和属性集合 datalist
     */
    public  void write2Shape(String shpPath, String encode, String geoType, String shpKey, List<ShpFiled> attrKeys, List<Map<String, Object>> data) {
        WKTReader reader = new WKTReader();
        try {
            //创建shape文件对象
            File file = new File(shpPath);
            Map<String, Serializable> params = new HashMap<>();
            params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
 
            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setCRS(DefaultGeographicCRS.WGS84);
            tb.setName("sx_test");
            tb.add("the_geom", getClass(geoType));
            for (ShpFiled field : attrKeys) {
                tb.add(field.getFiledname().toUpperCase(), getClass(field.getType()));
            }
            ds.createSchema(tb.buildFeatureType());
            //设置编码
            Charset charset = Charset.forName(encode);
            ds.setCharset(charset);
 
            //设置Writer
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
            //    写入文件信息
            for (int i = 0; i < data.size(); i++) {
 
                SimpleFeature feature = writer.next();
                Map<String, Object> row = data.get(i);
 
 
                Geometry geom = reader.read(row.get(shpKey).toString());
                feature.setAttribute("the_geom", geom);
                for (ShpFiled field : attrKeys) {
                    if (row.get(field.getFiledname()) != null) {
                        feature.setAttribute(field.getFiledname().toUpperCase(), row.get(field.getFiledname()));
                    } else {
                        feature.setAttribute(field.getFiledname().toUpperCase(), null);
                    }
                }
            }
            writer.write();
            writer.close();
            ds.dispose();
 
            //添加到压缩文件
            //zipShapeFile(shpPath);
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 更新shp文件数据
     *
     * @param path 文件路径
     * @param datalist 空间及属性数据
     */
    public static void updateFeature(String path, List<Map<String, Object>> datalist,String code) {
        ShapefileDataStore dataStore = null;
        File file = new File(path);
        Transaction transaction = new DefaultTransaction("handle");
        try {
            dataStore = new ShapefileDataStore(file.toURL());
            Charset charset = Charset.forName(code);
            dataStore.setCharset(charset);
            String typeName = dataStore.getTypeNames()[0];
            SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(typeName);
 
            // 获取字段列表
            SimpleFeatureType featureType = store.getSchema();
            List<String> fileds = getFileds(featureType);
            store.setTransaction(transaction);
            WKTReader reader = new WKTReader();
            for (Map<String, Object> data : datalist) {
 
                Filter filter = null;
                if (data.get("where") != null) {
                    filter = ECQL.toFilter(data.get("where").toString());
                }
 
                Object[] objs = new Object[] {};
                String[] str = new String[] {};
                if (data.get("geom") != null) {
                    Geometry geometry = reader.read(data.get("geom").toString());
                    str = add(str, "the_geom");
                    objs = add(objs, geometry);
 
                }
                for (String stri : fileds) {
                    if (data.get(stri) != null) {
 
                        str = add(str, stri);
                        objs = add(objs, data.get(stri));
                    }
                }
                store.modifyFeatures(str, objs, filter);
            }
 
            transaction.commit();
            System.out.println("========updateFeature====end====");
        } catch (Exception eek) {
            eek.printStackTrace();
            try {
                transaction.rollback();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
 
        }
 
    }
 
    /**
     * 移除shp中的数据
     * @param path 文件路径
     * @param ids 字段值数组
     * @param filed 字段名
     */
    public static void removeFeature(String path, List<String>ids,String filed,String code){
        ShapefileDataStore dataStore = null;
        File file = new File(path);
        Transaction transaction = new DefaultTransaction("handle");
        try {
            dataStore = new ShapefileDataStore(file.toURL());
            Charset charset = Charset.forName(code);
            dataStore.setCharset(charset);
            String typeName = dataStore.getTypeNames()[0];
            SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(typeName);
            store.setTransaction(transaction);
 
            Filter filter = null;
            if(ids.size()>0) {
                String join = filed +" in ("+StringUtils.join(ids,",")+")";
                System.out.println(join);
                filter = ECQL.toFilter(join);
            }
            if(filter!=null) {
 
                store.removeFeatures(filter);
                transaction.commit();
                System.out.println("======removeFeature== done ========");
            }
 
        } catch (Exception eek) {
            eek.printStackTrace();
            try {
                transaction.rollback();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
 
        }
 
    }
 
 
 
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2150830.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数字签名和CA数字证书的核心原理

看了蛋老师的视频就很容易理解了&#xff0c;首先对服务器的公钥和信息进行哈希运算得到一个短字符串&#xff0c;然后用CA机构中的私钥对这一短字符串进行加密就得到了一个数字签名&#xff0c;然后就这个数字签名放到数字证书中&#xff0c;同时服务器的公钥也放在数字证书中…

NFT Insider #148:The Sandbox 推出 SHIBUYA Y3K 时尚系列,Azuki 进军动漫 NFT 领域

市场数据 加密艺术及收藏品新闻 Infinex 新推 NFT 系列首四日销售额破4000万美元 尽管顶级 NFT 系列表现不佳&#xff0c;Infinex 的最新 NFT 系列在首四日内销售额已超过 4000 万美元。Infinex 是一个非托管平台&#xff0c;提供轻松访问链上协议和 dApp。 Infinex Core 的…

Day69补 前后端分离思想

ajax前后端分离 前后端分离处理&#xff1a;前端------&#xff08;数据&#xff09;-----服务端----&#xff08;数据&#xff09;-----前端-----动态改变页面的内容 1.json 1、JSON&#xff1a;由于JSON易读以及纯文本格式的特性&#xff0c;可以非常容易地与其他程序进行沟通…

引领长期投资新篇章:价值增长与财务安全的双重保障

随着全球金融市场的不断演变&#xff0c;长期投资策略因其稳健性和对价值增长的显著推动作用而日益受到投资者的重视。在这一背景下&#xff0c;Zeal Digital Shares&#xff08;ZDS&#xff09;项目以其创新的数字股票产品&#xff0c;为全球投资者提供了一个全新的长期投资平…

IPv6(四)

文章目录 Path MTUIPv6配置 Path MTU IPv4 对于数据过大的数据包会执行切片操作&#xff0c;但是切片有可能会造成设备性能的降低 IPv6使用Path MTU来传递数据过大的数据包 依次会协商最小的 MTU 单元为了减少中间转发设备的压力&#xff0c;中间转发设备不对 IPv6 报文进行分片…

【快速笔记】freeRTOS

第十八章 低功耗Tickless模式 睡眠模式:__WFI 中断唤醒 __WFE 事件唤醒 CPU CLK关闭 停止模式&#xff1a;RAM保持 中断唤醒 当 STM32F103 处于休眠模式的时候 Cortex-M3 内核停止运行&#xff0c;但是其他外设运行正常&#xff0c; 比如 NVIC、SRAM 等。 休眠模式的功耗比其他…

【Linux】环境部署kafka集群

目录 一、kafka简介 1. 主要特点 2.组件介绍 3.消息中间件的对比 二、环境准备 1.Java环境 2.Zookeeper环境 3.硬件环境集群 三、Zookeeper的集群部署 1.下载zookeeper 2.部署zookeeper集群 &#xff08;1&#xff09;node1节点服务器 &#xff08;2&#xff09;no…

排序----希尔排序

void ShellSort(int* a, int n) {int gap n;while (gap > 1){// 1保证最后一个gap一定是1// gap > 1时是预排序// gap 1时是插入排序gap gap / 3 1;for (size_t i 0; i < n - gap; i){int end i;int tmp a[end gap];while (end > 0){if (tmp < a[end]){…

6.C_数据结构_查询_哈希表

概述 哈希表的查询是通过计算的方式获取数据的地址&#xff0c;而不是依次比较。在哈希表中&#xff0c;有一个键值key&#xff0c;通过一些函数转换为哈希表的索引值。 其中&#xff1a;这个函数被称为哈希函数、散列函数、杂凑函数&#xff0c;记为&#xff1a;H(key) 哈希…

MySQL 中的锁定粒度:理解与应用

在 MySQL 数据库的使用中&#xff0c;锁定粒度是一个至关重要的概念。它决定了数据库在并发控制中锁定的范围和程度&#xff0c;对数据库的性能和并发能力有着深远的影响。今天&#xff0c;我们就来深入了解一下 MySQL 中的锁定粒度是什么意思&#xff0c;并通过实际案例来更好…

鸿蒙开发之ArkUI 界面篇 十五 交叉轴对其方式

鸿蒙界面有两个容器一个是Colum、一个是Row&#xff0c;Colum主轴是垂直方向&#xff0c;交叉轴是水平方向&#xff0c;Row的主轴是水平方向&#xff0c;交叉轴是垂直方向&#xff0c;对应方向调整子控件的话&#xff0c;justifyContent调整的是主轴方向的子控件距离&#xff0…

论文阅读-《Attention is All You Need》

注意力就是一切 【要点】&#xff1a;论文提出了一种全新的网络架构——Transformer&#xff0c;完全基于注意力机制&#xff0c;无需使用循环和卷积&#xff0c;实现了在机器翻译任务上的性能提升和训练效率的显著提高。 【方法】&#xff1a;通过构建一个仅使用注意力机制的…

【高分系列卫星简介】

高分系列卫星是中国国家高分辨率对地观测系统&#xff08;简称“高分工程”&#xff09;的重要组成部分&#xff0c;旨在提供全球范围内的高分辨率遥感数据&#xff0c;广泛应用于环境监测、灾害应急、城市规划、农业估产等多个领域。以下是对高分系列卫星及其数据、相关参数和…

Java流程控制语句——条件控制语句详解(附有流程图)#Java条件控制语句有哪些?#if-else、switch

在 Java 编程中&#xff0c;条件控制语句用于控制程序的执行路径&#xff0c;决定根据某些条件来选择执行某段代码或跳过某段代码。它们是 Java 编程的重要组成部分&#xff0c;帮助开发者根据不同的输入、状态或数据流来编写更加灵活和动态的代码。在本文中&#xff0c;我们将…

利用git将项目上传到github

采用git而不是在pycharm中共享的原因&#xff1a;可能会出现上图报错 目录 1、创建github仓库2、在 git bash 中初始化Git仓库&#xff0c;添加文件&#xff0c;上传代码 1、创建github仓库 2、在 git bash 中初始化Git仓库&#xff0c;添加文件&#xff0c;上传代码

【C++】STL----list常见用法

&#x1f525;个人主页&#x1f525;&#xff1a;孤寂大仙V &#x1f308;收录专栏&#x1f308;&#xff1a;C从小白到高手 &#x1f339;往期回顾&#x1f339;&#xff1a;[C]vector常见用法 &#x1f516; 流水不争&#xff0c;争的是滔滔不息。 文章目录 一、list的介绍li…

【C++】list容器的基本使用

一、list是什么 list的底层结构是带头双向循环链表。 相较于 vector 的连续线性空间&#xff0c;list 就显得复杂很多&#xff0c;它是由一个个结点构成&#xff0c;每个结点申请的空间并不是连续的&#xff0c;它的好处是每次插入或删除一个数据&#xff0c;就配置或释放一个…

WebServer:log

超时锁的编写 这个问题处于blockqueue.h文件中&#xff0c;内容如下&#xff1a; template<class T> bool BlockDeque<T>::pop(T& item, int timeout) {std::unique_lock<std::mutex> locker(mtx_);while(deq_.empty()) {if(condConsumer_.wait_for(lo…

内存泄漏

文章目录 内存泄漏发现问题topVisualVMArthas 原因分析代码层面并发请求 诊断问题MAT原理 –支配树获取运行时快照 内存泄漏 内存泄漏&#xff08;memory leak&#xff09;&#xff1a;在Java中如果不再使用一个对象&#xff0c;但是该对象依然在GC ROOT的引用链上&#xff0c;…

12.第二阶段x86游戏实战2-CE找基地址

免责声明&#xff1a;内容仅供学习参考&#xff0c;请合法利用知识&#xff0c;禁止进行违法犯罪活动&#xff01; 本次游戏没法给 内容参考于&#xff1a;微尘网络安全 本人写的内容纯属胡编乱造&#xff0c;全都是合成造假&#xff0c;仅仅只是为了娱乐&#xff0c;请不要…