功能说明:

  • 给一个tiff文件目录geotiff文件(tiff文件),转成c#二维数组
  • 给一个c#二维数组,转tiff文件

实现:

        public void CreateRasterFromModuleFilePath(string pDirectory, string pFileName,string pRasterFormat, string pFilePath_Module, System.Array pArray, object pNoDataValue){if (pDirectory == null || pDirectory == "" ||pFileName == null || pFileName == "" ||pRasterFormat == null || pRasterFormat == "")return;// create a temporary directorystring pDirectoryRandom = System.IO.Path.GetTempPath();pDirectoryRandom = System.IO.Path.GetDirectoryName(pDirectoryRandom);//if equal, create a new temp directory  if (pDirectoryRandom == pDirectory){string pRandom = System.Guid.NewGuid().ToString().Substring(0, 5);pDirectoryRandom = pDirectory + pRandom;System.IO.Directory.CreateDirectory(pDirectoryRandom);}Gdal.AllRegister();Dataset ds = Gdal.Open(pFilePath_Module, Access.GA_ReadOnly);// columns(xSize) and rows(ySize) of rastersint xSize     = ds.RasterXSize;int ySize     = ds.RasterYSize;//important for making sure the cellsize   int bandCount = ds.RasterCount;// columns and rows of the pArrayint countRow = pArray.GetLength(0);     //1342int countColumn = pArray.GetLength(1);  //1694// Make sure the new Geotiff file named pFileName has the same cellsize.bool diagnosis = ((xSize == countColumn) && (ySize == countRow));Debug.Assert(diagnosis, "The size should be the same between input Array and geotiff module!");double[] transform = new double[6] { 0, 0, 0, 0, 0, 0 };ds.GetGeoTransform(transform);//// get the information of Spatial Referencestring projection = ds.GetProjection();//DataType dataType = ds.GetRasterBand(1).DataType;string rasterFormat = null;if (pRasterFormat == "TIFF") rasterFormat = "GTiff";else Debug.Assert(true, "unsupported data type now for RasterFormat!");OSGeo.GDAL.Driver driver = Gdal.GetDriverByName(rasterFormat);string geotiffOutputPath = pDirectoryRandom + "\\" + pFileName;//delete the old version of fileif (System.IO.File.Exists(geotiffOutputPath)){System.IO.File.Delete(geotiffOutputPath);}Dataset result = driver.Create(geotiffOutputPath, countColumn, countRow, bandCount, dataType, null);//set attributesresult.SetGeoTransform(transform);result.SetProjection(projection);OSGeo.GDAL.CPLErr check = 0;if (pArray.GetValue(0, 0).GetType() == typeof(int)){int[] tmpData = new int[countColumn * countRow];int tmp = 0;for (int i = 0; i < countRow; ++i){for (int j = 0; j < countColumn; ++j){tmp = (int)pArray.GetValue(i, j);tmpData[i * countColumn + j] = tmp;}}//writer geotiff data to filetry{//result.GetRasterBand(1).SetNoDataValue((int)pNoDataValue);    // Langping's implementation in file ALSAToolsAE.cs but with some warnings when transferring                                                                                                       result.GetRasterBand(1).SetNoDataValue( ALSAGlobal.pNoDataInt); // john's improvement}catch (System.Exception ex){Console.WriteLine("{0}: result.GetRasterBand(1).SetNoDataValue((int)pNoDataValue)  failed !", ex.ToString());}// The value of xoff and yoff indicates the location that the upper left corner of the pixel block is to write.check = result.GetRasterBand(1).WriteRaster(0, 0, countColumn, countRow, tmpData, countColumn, countRow, 0, 0);}else if (pArray.GetValue(0, 0).GetType() == typeof(float)){float[] tmpData = new float[countColumn * countRow];float tmp = 0;for (int i = 0; i < countRow; ++i){for (int j = 0; j < countColumn; ++j){tmp = (float)pArray.GetValue(i, j);tmpData[i * countColumn + j] = tmp;}}//writer geotiff data to filetry{// result.GetRasterBand(1).SetNoDataValue((float)pNoDataValue); // Lang ping's implementation in file ALSAToolsAE.cs but with some warnings when transferringresult.GetRasterBand(1).SetNoDataValue(ALSAGlobal.pNoDataFloat);// john's improvement}catch (System.Exception ex){Console.WriteLine("{0}: result.GetRasterBand(1).SetNoDataValue((int)pNoDataValue)  failed !", ex.ToString());}                                                                                          // The value of xoff and yoff indicates the location that the upper left corner of the pixel block is to write.check = result.GetRasterBand(1).WriteRaster(0, 0, countColumn, countRow, tmpData, countColumn, countRow, 0, 0);}else{Debug.Assert(true, "unsupported data type now for pArray!");}result.GetRasterBand(1).FlushCache();result.FlushCache();if (check == OSGeo.GDAL.CPLErr.CE_Failure || check == OSGeo.GDAL.CPLErr.CE_Fatal)Debug.Assert(false, "write tmp geotiff failed!");}public System.Array GetRasterValuesFromFilePath(string pFilePath, bool pBoolBool){if (pFilePath == null){//if nullreturn null;}if (!System.IO.File.Exists(pFilePath)){return null;}Gdal.AllRegister();Dataset ds = Gdal.Open(pFilePath, Access.GA_ReadOnly);Band band = ds.GetRasterBand(1);int width = ds.RasterXSize;int height = ds.RasterYSize;if (band.DataType == DataType.GDT_Float32){System.Array resultArray = Array.CreateInstance(typeof(float), height, width);float[] buffer = new float[width * height];band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);for (int i = 0; i < buffer.Length; i++)resultArray.SetValue(buffer[i], i / width, i % width);return resultArray;}if (band.DataType == DataType.GDT_Byte) {if (pBoolBool){// transform geotiff file to bool arraySystem.Array resultArray = Array.CreateInstance(typeof(bool), height, width);byte[] buffer = new byte[width * height];band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);for (int i = 0; i < buffer.Length; i++)resultArray.SetValue((buffer[i] == 0 ? false : true), i / width, i % width);return resultArray;}else{System.Array resultArray = Array.CreateInstance(typeof(byte), height, width);byte[] buffer = new byte[width * height];band.ReadRaster(0, 0, width, height, buffer, width, height, 0, 0);for (int i = 0; i < buffer.Length; i++)resultArray.SetValue(buffer[i], i / width, i % width);return resultArray;}}ds.Dispose();Debug.Assert(true, "unsupported data type now!");return null;}

GIS_gdal geotiff文件与C# 数组array之间的转换相关推荐

  1. C# 对象、文件与二进制串(byte数组)之间的转换

    1.关于本文 在使用C#下的TCP(类TcpClient).UDP(类UdpClient)协议传输信息时,都需要将信息转换为byte类型的数组进行发送.本文实现了两种object与byte数组的转换和 ...

  2. 关于数组集合之间的转换

    开发中经常用到数组和集合之间的转换和集合与集合之间的转换. 在JDK中有现成的API中供我们使用. 1.首先是数组和集合之间的转换: 1 import java.util.ArrayList; 2 i ...

  3. Java List和Array之间的转换

    一.Array 转为List1.实现方法 :java中数组转list使用Arrays.asList(T... a)方法.public class Array2List {public static v ...

  4. json字符串、json对象、数组 三者之间的转换

    json字符串转化成json对象 // jquery的方法 var jsonObj = $.parseJSON(jsonStr) //js 的方法 var jsonObj = JSON.parse(j ...

  5. vue将json字符串转换为数组_json字符串、json对象、数组 三者之间的转换

    var Obj = JOSN.parse("cscac"); //将JSON字符串转换成JSON对象 var "cscac" = JSON.stringify( ...

  6. 序列化之对象,字符串,byte数组,XML之间的转换(一)

    工作一年多了,越来越感到自己不能这样一直下去,在最好的青春里面却已经死了.被时间消磨了意志,被工作杀死了精神.我想,我只要活着,我就要去不断的要求自己,不断的去追求更高的山峰. 放眼四周,有趣的灵魂越 ...

  7. C# Object与二进制串(byte数组)之间的转换

    话不多说,看连接 这里是连接 [1]: 转换一. [2]: 转换二.

  8. json c语言 数组转字符串数组中,json和字符串/数组/集合的互相转换の神操作总结...

    一:前端字符串转JSON的4种方式 1,eval方式解析,恐怕这是最早的解析方式了. function strToJson(str){ var json = eval('(' + str + ')') ...

  9. python代码转换为pytorch_pytorch实现Tensor变量之间的转换

    系统默认是torch.FloatTensor类型 data = torch.Tensor(2,3)是一个2*3的张量,类型为FloatTensor data.cuda()就转换为GPU的张量类型,to ...

  10. java类型之间的转换_java类型之间的转换

    string和int之间的转换? 字符串转换成数据 Java代码 String MyNumber ="1234"; intMyInt = Integer.parseInt(MyNu ...

最新文章

  1. oc09--NSString
  2. c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2
  3. Redis整合Spring结合使用缓存实例(转)
  4. U3D非常诡异的【结构体引用】现象-个例
  5. c#写字板实现加粗功能_Windows 7中写字板和绘画中的新功能
  6. dev.c drv.c bus.c
  7. [转] 为你的项目选择一个合适的开源协议
  8. c语言求英文字母编号,菜鸟求助,写一个随机输出26个英文字母的程序
  9. 20175320 2018-2019-2 《Java程序设计》第8周学习总结
  10. 计算机建筑制图实践报告,工程建筑实习报告范文(精选5篇)
  11. 磁共振影像分析之: 基于FSL的VBM分析(2)
  12. php做购物商品库存解决方法
  13. ln命令 Linux软连接(Symbolic Link)和硬链接(Hard Link)
  14. 论文解读(PairNorm)《PairNorm: Tackling Oversmoothing in GNNs》
  15. 安卓动画开始,暂停和停止
  16. 窥探SQL: 2.基础查询与排序
  17. 本周大新闻|128GB版Quest 2再降价,Mojo Vision完成“新A轮”融资
  18. YOLOv5的一些评价指标(训练图的中文解释)
  19. 积分排名页面 html,欧洲联赛排名积分榜
  20. 小哥allegro72讲视频百度云下载

热门文章

  1. 《数学之美》—信息的度量和作用
  2. [Bzoj1143][CTSC2008]祭祀river
  3. leetcode77
  4. Mybatis sqlsession解析
  5. pta 编程题10 Root of AVL Tree
  6. T-SQL查询进阶—理解SQL Server中的锁
  7. 使用eclipse搭建maven项目Java web项目
  8. 分享一次学习中遇到的问题
  9. SQL Server 字符串拆分
  10. Sublime Text一个小插件——SideBarEnhancements