// todo cleanup and add support for adding external palettes. private Bitmap GetBitmapDirect(Dataset dataset, int xOff, int yOff, int width, int height, int imageWidth, int imageHeight) { if (dataset.RasterCount == 0) { return(null); } ImageSettings settings = CreateSettings(PixelFormat.Undefined, 0); DataType dataType = dataset.GetRasterBand(1).DataType; if (dataset.GetDriver().ShortName.Equals("EHdr") && dataset.RasterCount == 1) // 1-band ESRI BIL/BIP/BSQ files from Habitat { settings = GetDefaultImageSettings(dataset, true); } else if (dataset.GetDriver().ShortName.Equals("GTiff")) // GeoTIFF files { settings = CreateSettings(PixelFormat.Format8bppIndexed, 1); } else // default for all other GDAL supported formats { settings = GetDefaultImageSettings(dataset, false); } PixelFormat pixelFormat = settings.pixelFormat; int targetPixelSpace = settings.targetPixelSpace; //// Create a Bitmap to store the GDAL image in var bitmap = new Bitmap(imageWidth, imageHeight, pixelFormat); // Use GDAL raster reading methods to read the image data directly into the Bitmap var bitmapData = bitmap.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), ImageLockMode.ReadWrite, pixelFormat); try { log.InfoFormat("lineSpace: {0} pixelSpace: {1}", bitmapData.Stride, targetPixelSpace); //special rendering for bil file: this is ugly if (dataset.GetDriver().ShortName.Equals("EHdr") && dataset.RasterCount == 1) { string legendFilename = gdalFeatureFeatureProvider.Path.Substring(0, gdalFeatureFeatureProvider.Path.LastIndexOf('.')) + ".leg"; if (HasFloatingDataType(dataset)) { FillBitmap <float>(bitmap, bitmapData, dataset, xOff, yOff, width, height, imageWidth, imageHeight, targetPixelSpace, bitmapData.Stride, legendFilename); } else { FillBitmap <int>(bitmap, bitmapData, dataset, xOff, yOff, width, height, imageWidth, imageHeight, targetPixelSpace, bitmapData.Stride, legendFilename); } } else { int[] bandMap = new int[4] { 1, 1, 1, 1 }; int channelCount = 1; bool hasAlpha = false; bool isIndexed = false; int channelSize = 8; ColorTable ct = null; // Evaluate the bands and find out a proper image transfer format for (int i = 0; i < dataset.RasterCount; i++) { Band band = dataset.GetRasterBand(i + 1); if (Gdal.GetDataTypeSize(band.DataType) > 8) { channelSize = 16; } switch (band.GetRasterColorInterpretation()) { case ColorInterp.GCI_AlphaBand: channelCount = 4; hasAlpha = true; bandMap[3] = i + 1; break; case ColorInterp.GCI_BlueBand: if (channelCount < 3) { channelCount = 3; } bandMap[0] = i + 1; break; case ColorInterp.GCI_RedBand: if (channelCount < 3) { channelCount = 3; } bandMap[2] = i + 1; break; case ColorInterp.GCI_GreenBand: if (channelCount < 3) { channelCount = 3; } bandMap[1] = i + 1; break; case ColorInterp.GCI_PaletteIndex: ct = band.GetRasterColorTable(); isIndexed = true; bandMap[0] = i + 1; break; case ColorInterp.GCI_GrayIndex: isIndexed = true; bandMap[0] = i + 1; break; default: // we create the bandmap using the dataset ordering by default if (i < 4 && bandMap[i] == 0) { if (channelCount < i) { channelCount = i; } bandMap[i] = i + 1; } break; } } // find out the pixel format based on the gathered information //PixelFormat pixelFormat; //DataType dataType; int pixelSpace; if (isIndexed) { //pixelFormat = PixelFormat.Format8bppIndexed; dataType = DataType.GDT_Byte; pixelSpace = 1; } else { if (channelCount == 1) { if (channelSize > 8) { // pixelFormat = PixelFormat.Format16bppGrayScale; dataType = DataType.GDT_Int16; pixelSpace = 2; } else { // pixelFormat = PixelFormat.Format24bppRgb; channelCount = 3; dataType = DataType.GDT_Byte; pixelSpace = 3; } } else { if (hasAlpha) { if (channelSize > 8) { // pixelFormat = PixelFormat.Format64bppArgb; dataType = DataType.GDT_UInt16; pixelSpace = 8; } else { // pixelFormat = PixelFormat.Format32bppArgb; dataType = DataType.GDT_Byte; pixelSpace = 4; } channelCount = 4; } else { if (channelSize > 8) { // pixelFormat = PixelFormat.Format48bppRgb; dataType = DataType.GDT_UInt16; pixelSpace = 6; } else { // pixelFormat = PixelFormat.Format24bppRgb; dataType = DataType.GDT_Byte; pixelSpace = 3; } channelCount = 3; } } } SetColorPalette(dataset, bitmap); // Use GDAL raster reading methods to read the image data directly into the Bitmap //dataset.ReadRaster(xOff, yOff, width, height, bitmapData.Scan0, imageWidth, imageHeight, dataType, // dataset.RasterCount, targetPixelSpace, bitmapData.Stride, bandSpace); int stride = bitmapData.Stride; IntPtr buf = bitmapData.Scan0; dataset.ReadRaster(xOff, yOff, width, height, buf, imageWidth, imageHeight, dataType, channelCount, bandMap, pixelSpace, stride, 1); } } finally { if (bitmapData != null) { bitmap.UnlockBits(bitmapData); } } return(bitmap); }
private static void SaveBitmapDirect(string filename, Dataset ds, int xOff, int yOff, int width, int height, int imageWidth, int imageHeight) { if (ds.RasterCount == 0) { return; } int[] bandMap = new int[4] { 1, 1, 1, 1 }; int channelCount = 1; bool hasAlpha = false; bool isIndexed = false; int channelSize = 8; ColorTable ct = null; // Evaluate the bands and find out a proper image transfer format for (int i = 0; i < ds.RasterCount; i++) { Band band = ds.GetRasterBand(i + 1); if (Gdal.GetDataTypeSize(band.DataType) > 8) { channelSize = 16; } switch (band.GetRasterColorInterpretation()) { case ColorInterp.GCI_AlphaBand: channelCount = 4; hasAlpha = true; bandMap[3] = i + 1; break; case ColorInterp.GCI_BlueBand: if (channelCount < 3) { channelCount = 3; } bandMap[0] = i + 1; break; case ColorInterp.GCI_RedBand: if (channelCount < 3) { channelCount = 3; } bandMap[2] = i + 1; break; case ColorInterp.GCI_GreenBand: if (channelCount < 3) { channelCount = 3; } bandMap[1] = i + 1; break; case ColorInterp.GCI_PaletteIndex: ct = band.GetRasterColorTable(); isIndexed = true; bandMap[0] = i + 1; break; case ColorInterp.GCI_GrayIndex: isIndexed = true; bandMap[0] = i + 1; break; default: // we create the bandmap using the dataset ordering by default if (i < 4 && bandMap[i] == 0) { if (channelCount < i) { channelCount = i; } bandMap[i] = i + 1; } break; } } // find out the pixel format based on the gathered information PixelFormat pixelFormat; DataType dataType; int pixelSpace; if (isIndexed) { pixelFormat = PixelFormat.Format8bppIndexed; dataType = DataType.GDT_Byte; pixelSpace = 1; } else { if (channelCount == 1) { if (channelSize > 8) { pixelFormat = PixelFormat.Format16bppGrayScale; dataType = DataType.GDT_Int16; pixelSpace = 2; } else { pixelFormat = PixelFormat.Format24bppRgb; channelCount = 3; dataType = DataType.GDT_Byte; pixelSpace = 3; } } else { if (hasAlpha) { if (channelSize > 8) { pixelFormat = PixelFormat.Format64bppArgb; dataType = DataType.GDT_UInt16; pixelSpace = 8; } else { pixelFormat = PixelFormat.Format32bppArgb; dataType = DataType.GDT_Byte; pixelSpace = 4; } channelCount = 4; } else { if (channelSize > 8) { pixelFormat = PixelFormat.Format48bppRgb; dataType = DataType.GDT_UInt16; pixelSpace = 6; } else { pixelFormat = PixelFormat.Format24bppRgb; dataType = DataType.GDT_Byte; pixelSpace = 3; } channelCount = 3; } } } // Create a Bitmap to store the GDAL image in Bitmap bitmap = new Bitmap(imageWidth, imageHeight, pixelFormat); if (isIndexed) { // setting up the color table if (ct != null) { int iCol = ct.GetCount(); ColorPalette pal = bitmap.Palette; for (int i = 0; i < iCol; i++) { ColorEntry ce = ct.GetColorEntry(i); pal.Entries[i] = Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3); } bitmap.Palette = pal; } else { // grayscale ColorPalette pal = bitmap.Palette; for (int i = 0; i < 256; i++) { pal.Entries[i] = Color.FromArgb(255, i, i, i); } bitmap.Palette = pal; } } // Use GDAL raster reading methods to read the image data directly into the Bitmap BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), ImageLockMode.ReadWrite, pixelFormat); try { int stride = bitmapData.Stride; System.IntPtr buf = bitmapData.Scan0; using (RasterIOExtraArg arg = new RasterIOExtraArg()) { GCHandle handle = GCHandle.Alloc("Test data", GCHandleType.Pinned); try { arg.nVersion = argVersion; arg.eResampleAlg = resampleAlg; arg.pfnProgress = new Gdal.GDALProgressFuncDelegate(ProgressFunc); arg.pProgressData = handle.AddrOfPinnedObject(); // or System.IntPtr.Zero if not data to be added; arg.bFloatingPointWindowValidity = 0; ds.ReadRaster(xOff, yOff, width, height, buf, imageWidth, imageHeight, dataType, channelCount, bandMap, pixelSpace, stride, 1, arg); } finally { handle.Free(); } } } finally { bitmap.UnlockBits(bitmapData); } bitmap.Save(filename); }
private Bitmap ReadRgbBitmap(int xOffset, int yOffset, int width, int height) { int[] bandMap = new int[4] { 0, 0, 0, 0 }; int channelCount = 1; bool hasAlpha = false; bool isIndexed = false; int channelSize = 8; ColorTable colorTable = null; if (xOffset + width > dataset.RasterXSize) { width = dataset.RasterXSize - xOffset; } if (yOffset + height > dataset.RasterYSize) { height = dataset.RasterYSize - yOffset; } // Evaluate the bands and find out a proper image transfer format for (int i = 0; i < dataset.RasterCount; i++) { Band band = dataset.GetRasterBand(i + 1); if (Gdal.GetDataTypeSize(band.DataType) > 8) { channelSize = 16; } switch (band.GetRasterColorInterpretation()) { case ColorInterp.GCI_AlphaBand: channelCount = 4; hasAlpha = true; bandMap[3] = i + 1; break; case ColorInterp.GCI_BlueBand: if (channelCount < 3) { channelCount = 3; } bandMap[0] = i + 1; break; case ColorInterp.GCI_RedBand: if (channelCount < 3) { channelCount = 3; } bandMap[2] = i + 1; break; case ColorInterp.GCI_GreenBand: if (channelCount < 3) { channelCount = 3; } bandMap[1] = i + 1; break; case ColorInterp.GCI_PaletteIndex: colorTable = band.GetRasterColorTable(); isIndexed = true; bandMap[0] = i + 1; break; case ColorInterp.GCI_GrayIndex: isIndexed = true; bandMap[0] = i + 1; break; default: // we create the bandmap using the dataset ordering by default if (i < 4 && bandMap[i] == 0) { if (channelCount < i) { channelCount = i; } bandMap[i] = i + 1; } break; } } // find out the pixel format based on the gathered information PixelFormat pixelFormat; DataType dataType; int pixelSpace; if (isIndexed) { pixelFormat = PixelFormat.Format8bppIndexed; dataType = DataType.GDT_Byte; pixelSpace = 1; } else { if (channelCount == 1) { if (channelSize > 8) { pixelFormat = PixelFormat.Format16bppGrayScale; dataType = DataType.GDT_Int16; pixelSpace = 2; } else { pixelFormat = PixelFormat.Format24bppRgb; channelCount = 3; dataType = DataType.GDT_Byte; pixelSpace = 3; } } else { if (hasAlpha) { if (channelSize > 8) { pixelFormat = PixelFormat.Format64bppArgb; dataType = DataType.GDT_UInt16; pixelSpace = 8; } else { pixelFormat = PixelFormat.Format32bppArgb; dataType = DataType.GDT_Byte; pixelSpace = 4; } channelCount = 4; } else { if (channelSize > 8) { pixelFormat = PixelFormat.Format48bppRgb; dataType = DataType.GDT_UInt16; pixelSpace = 6; } else { pixelFormat = PixelFormat.Format24bppRgb; dataType = DataType.GDT_Byte; pixelSpace = 3; } channelCount = 3; } } } Bitmap bitmap = new Bitmap(width, height, pixelFormat); if (isIndexed) { if (colorTable != null) { ColorPalette pal = bitmap.Palette; for (int i = 0; i < colorTable.GetCount(); i++) { ColorEntry ce = colorTable.GetColorEntry(i); pal.Entries[i] = Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3); } bitmap.Palette = pal; } else { ColorPalette pal = bitmap.Palette; for (int i = 0; i < 255; i++) { pal.Entries[i] = Color.FromArgb(255, i, i, i); } bitmap.Palette = pal; } } // Use GDAL raster reading methods to read the image data directly into the Bitmap BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, pixelFormat); try { int stride = bitmapData.Stride; IntPtr buf = bitmapData.Scan0; dataset.ReadRaster(xOffset, yOffset, width, height, buf, width, height, dataType, channelCount, bandMap, pixelSpace, stride, 1); } finally { bitmap.UnlockBits(bitmapData); } return(bitmap); }
private static Bitmap CreateCompatibleBitmap(Dataset ds, int imageWidth, int imageHeight) { if (ds.RasterCount == 0) { return(null); } bandMap = new int[4] { 1, 1, 1, 1 }; channelCount = 1; hasAlpha = false; isPremultiplied = false; isIndexed = false; channelSize = 8; // Evaluate the bands and find out a proper image transfer format for (int i = 0; i < ds.RasterCount; i++) { Band band = ds.GetRasterBand(i + 1); if (Gdal.GetDataTypeSize(band.DataType) > 8) { channelSize = 16; } // retrieving the premultiplied alpha flag string[] metadata = band.GetMetadata(""); for (int iMeta = 0; iMeta < metadata.Length; iMeta++) { if (metadata[iMeta].StartsWith("PREMULTIPLIED_ALPHA")) { isPremultiplied = true; } } switch (band.GetRasterColorInterpretation()) { case ColorInterp.GCI_AlphaBand: channelCount = 4; hasAlpha = true; bandMap[3] = i + 1; break; case ColorInterp.GCI_BlueBand: if (channelCount < 3) { channelCount = 3; } bandMap[0] = i + 1; break; case ColorInterp.GCI_RedBand: if (channelCount < 3) { channelCount = 3; } bandMap[2] = i + 1; break; case ColorInterp.GCI_GreenBand: if (channelCount < 3) { channelCount = 3; } bandMap[1] = i + 1; break; case ColorInterp.GCI_PaletteIndex: ct = band.GetRasterColorTable(); isIndexed = true; bandMap[0] = i + 1; break; case ColorInterp.GCI_GrayIndex: isIndexed = true; bandMap[0] = i + 1; break; default: // we create the bandmap using the dataset ordering by default if (i < 4 && bandMap[i] == 0) { if (channelCount < i) { channelCount = i; } bandMap[i] = i + 1; } break; } } // find out the pixel format based on the gathered information if (isIndexed) { pixelFormat = PixelFormat.Format8bppIndexed; dataType = DataType.GDT_Byte; pixelSpace = 1; } else { if (channelCount == 1) { if (channelSize > 8) { pixelFormat = PixelFormat.Format16bppGrayScale; dataType = DataType.GDT_Int16; pixelSpace = 2; } else { pixelFormat = PixelFormat.Format24bppRgb; channelCount = 3; dataType = DataType.GDT_Byte; pixelSpace = 3; } } else { if (hasAlpha) { if (channelSize > 8) { if (isPremultiplied) { pixelFormat = PixelFormat.Format64bppArgb; } else { pixelFormat = PixelFormat.Format64bppPArgb; } dataType = DataType.GDT_UInt16; pixelSpace = 8; } else { if (isPremultiplied) { pixelFormat = PixelFormat.Format32bppPArgb; } else { pixelFormat = PixelFormat.Format32bppArgb; } dataType = DataType.GDT_Byte; pixelSpace = 4; } channelCount = 4; } else { if (channelSize > 8) { pixelFormat = PixelFormat.Format48bppRgb; dataType = DataType.GDT_UInt16; pixelSpace = 6; } else { pixelFormat = PixelFormat.Format24bppRgb; dataType = DataType.GDT_Byte; pixelSpace = 3; } channelCount = 3; } } } // Create a Bitmap to store the GDAL image in return(new Bitmap(imageWidth, imageHeight, pixelFormat)); }
private RenderInformation DetermineRenderInformation(Dataset dataset) { bool hasAlpha = false; bool isIndexed = false; int channelSize = -1; ColorTable colorTable = null; RenderInformation info = new RenderInformation { BandMap = new[] { 1, 1, 1, 1 }, ChannelCount = dataset.RasterCount }; foreach (int i in Enumerable.Range(0, info.ChannelCount)) { int bandNumber = i + 1; using (Band band = dataset.GetRasterBand(bandNumber)) { channelSize = Gdal.GetDataTypeSize(band.DataType); switch (band.GetRasterColorInterpretation()) { case ColorInterp.GCI_RedBand: info.BandMap[2] = bandNumber; break; case ColorInterp.GCI_GreenBand: info.BandMap[1] = bandNumber; break; case ColorInterp.GCI_BlueBand: info.BandMap[0] = bandNumber; break; case ColorInterp.GCI_AlphaBand: hasAlpha = true; info.BandMap[3] = bandNumber; break; case ColorInterp.GCI_PaletteIndex: colorTable = band.GetRasterColorTable(); isIndexed = true; info.BandMap[0] = bandNumber; break; case ColorInterp.GCI_GrayIndex: isIndexed = true; info.BandMap[0] = bandNumber; break; default: if (i < 4 && info.BandMap[i] == 0) { info.ChannelCount = Math.Min(info.ChannelCount, bandNumber - 1); info.BandMap[i] = bandNumber; } break; } } } if (isIndexed) { info.PixelFormat = PixelFormats.Indexed8; info.PixelSpace = 1; if (colorTable == null) { info.Colors = BitmapPalettes.Gray256Transparent; } else { var colors = new List <Color>(); for (var i = 0; i < colorTable.GetCount(); i++) { var color = colorTable.GetColorEntry(i); colors.Add(Color.FromArgb((byte)color.c4, (byte)color.c1, (byte)color.c2, (byte)color.c3)); } info.Colors = new BitmapPalette(colors); } } else { int multiplier = channelSize / 8; if (info.ChannelCount == 1) { info.PixelFormat = channelSize > 8 ? PixelFormats.Gray16 : PixelFormats.Gray8; info.PixelSpace = multiplier; } else { if (hasAlpha) { info.PixelFormat = channelSize > 8 ? PixelFormats.Rgba64 : PixelFormats.Bgra32; } else { info.PixelFormat = channelSize > 8 ? PixelFormats.Rgb48 : PixelFormats.Bgr24; } info.PixelSpace = multiplier * info.ChannelCount; } } return(info); }
public GDAL_Info(Dataset ds) { Projection = ds.GetProjectionRef(); Resolution = new Size(ds.RasterXSize, ds.RasterYSize); Bands = new DataBandInfo[ds.RasterCount]; for (int i = 0; i < ds.RasterCount; i++) { Band band = ds.GetRasterBand(i + 1); Bands[i] = new DataBandInfo(); int temp; band.GetMaximum(out Bands[i].MaxValue, out temp); band.GetMaximum(out Bands[i].MinValue, out temp); band.GetNoDataValue(out Bands[i].NODATAValue, out temp); ColorInterp clr = band.GetRasterColorInterpretation(); switch (clr) { case ColorInterp.GCI_RedBand: Bands[i].Name = "RedBand"; Bands[i].Image = Resource1.red_layer; BppType += "R"; break; case ColorInterp.GCI_GreenBand: Bands[i].Name = "GreenBand"; Bands[i].Image = Resource1.green_layer; BppType += "G"; break; case ColorInterp.GCI_BlueBand: Bands[i].Name = "BlueBand"; Bands[i].Image = Resource1.blue_layer; BppType += "B"; break; default: Bands[i].Name = clr.ToString(); Bands[i].Image = null; BppType += "?"; break; } BppType += "[" + Gdal.GetDataTypeName(band.DataType) + "]"; Bpp += (ushort)Gdal.GetDataTypeSize(band.DataType); if (i + 1 < ds.RasterCount) { BppType += ","; } } BppType += " (" + Bpp + ")"; Driver = ds.GetDriver().LongName; Metadata = ds.GetMetadata(""); ImgMetadata = ds.GetMetadata("IMAGE_STRUCTURE"); SubDSMetadata = ds.GetMetadata("SUBDATASETS"); GeoLocMetadata = ds.GetMetadata("GEOLOCATION"); GDALInfoGetPosition(ds, 0.0, 0.0, out UpperLeftX, out UpperLeftY); GDALInfoGetPosition(ds, 0.0, ds.RasterYSize, out UpperRightX, out UpperRightY); GDALInfoGetPosition(ds, ds.RasterXSize, 0.0, out LowerLeftX, out LowerLeftY); GDALInfoGetPosition(ds, ds.RasterXSize, ds.RasterYSize, out LowerRightX, out LowerRightY); GDALInfoGetPosition(ds, ds.RasterXSize / 2, ds.RasterYSize / 2, out CenterX, out CenterY); }
protected override void ProcessRecord() { var dataset = Gdal.Open(Path, Access.GA_ReadOnly); Driver drv = dataset.GetDriver(); //Console.WriteLine("number of things is:"); //Console.WriteLine(dataset.RasterCount); //band numbers start at 1 var heightdata = dataset.GetRasterBand(1); double[] minmax = new double[2]; heightdata.ComputeRasterMinMax(minmax, 0); Console.WriteLine($"minmax is {minmax[0]}, {minmax[1]}"); if (Stats) { var statblock = new Dictionary <string, object>(); statblock.Add("XSize", heightdata.XSize); statblock.Add("YSize", heightdata.YSize); statblock.Add("ZMin", minmax[0]); statblock.Add("ZMax", minmax[1]); WriteObject(statblock); return; } //decide what max and min index should be int YMinIndex; int YMaxIndex; (YMinIndex, YMaxIndex) = GetMinMax(YMin, YMax, heightdata.YSize); int XMinIndex; int XMaxIndex; (XMinIndex, XMaxIndex) = GetMinMax(XMin, XMax, heightdata.XSize); int YIndexSize = YMaxIndex - YMinIndex; int XIndexSize = XMaxIndex - XMinIndex; //our buffer indices go from 0 to xxx int bufferXIndexSize = XIndexSize / Stride; int bufferYIndexSize = YIndexSize / Stride; //create a buffer to hold data in memory. double[] databuffer = new double[bufferXIndexSize * bufferYIndexSize]; heightdata.ReadRaster(XMinIndex, YMinIndex, XIndexSize, YIndexSize, databuffer, bufferXIndexSize, bufferYIndexSize, 0, 0); //misc stuff heightdata.GetNoDataValue(out double nodataval, out int hasnodataval); Console.WriteLine($"has nodata val: {hasnodataval}, is {nodataval}"); var thing = heightdata.GetRasterColorInterpretation(); var thing2 = Gdal.GetDataTypeSize(heightdata.DataType); using (var outfile = new STLExporter(Destination, !Text)) { if (RenderFaces) { for (int bufferYIndex = 0; bufferYIndex < bufferYIndexSize - 1; ++bufferYIndex) { for (int bufferXIndex = 0; bufferXIndex < bufferXIndexSize - 1; ++bufferXIndex) { int index = bufferYIndex * bufferXIndexSize + bufferXIndex; int xValue = bufferXIndex * Stride + XMinIndex; int yValue = bufferYIndex * Stride + YMinIndex; double zvalue = databuffer[index]; Vector3 pointA = new Vector3((float)(xValue * Scale), (float)(yValue * Scale), (float)(zvalue * Scale)); Vector3 pointB = new Vector3((float)(xValue * Scale), (float)((yValue + Stride) * Scale), (float)(databuffer[index + bufferXIndexSize] * Scale)); Vector3 pointC = new Vector3((float)((xValue + Stride) * Scale), (float)(yValue * Scale), (float)(databuffer[index + 1] * Scale)); Vector3 pointD = new Vector3((float)((xValue + Stride) * Scale), (float)((yValue + Stride) * Scale), (float)(databuffer[index + 1 + bufferXIndexSize] * Scale)); outfile.WriteTriangle(pointA, pointB, pointC); outfile.WriteTriangle(pointB, pointC, pointD); } } } else { for (int bufferYIndex = 0; bufferYIndex < bufferYIndexSize; ++bufferYIndex) { for (int bufferXIndex = 0; bufferXIndex < bufferXIndexSize; ++bufferXIndex) { int index = bufferYIndex * bufferXIndexSize + bufferXIndex; int xValue = bufferXIndex * Stride + XMinIndex; int yValue = bufferYIndex * Stride + YMinIndex; double zvalue = databuffer[index]; outfile.WritePoint((float)(xValue * Scale), (float)(yValue * Scale), (float)(zvalue * Scale)); } } } } //if we want to do triangles, we need: //x,y, x+1,y, x,y+1, x+1,y, x, y+1, x+1, y+1. Console.WriteLine($"end"); }
public bool TiffToKml(string inPut, string outPut, int band = 1) { FileInfo inPutFile = new FileInfo(inPut); bool isExtif = false; bool isExtiff = false; //입력 파일이 없다면 종료 if (!inPutFile.Exists) { return(false); } else { //입력 파일이 tif / tiff 파일이 아니라면 종료 if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff") { return(false); } if (inPutFile.Extension == ".tif") { isExtif = true; } if (inPutFile.Extension == ".tiff") { isExtiff = true; } } Gdal.AllRegister(); try { #region Get Coordinate double north = 36.16465526448886; //북 double south = 35.97362616042732; //남 double east = 127.5672085281825; //동 double west = 127.3435070025512; //서 Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly); string t_srs_wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]"; string s_srs_wkt = dataset.GetProjectionRef(); Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0.125); string[] options = null; OSGeo.GDAL.Driver srcDrv = Gdal.GetDriverByName("GTiff"); FileInfo outPutFile = new FileInfo(outPut); string testPath = string.Empty; if (isExtif) { testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tif", ".png")); } else if (isExtiff) { testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tiff", ".png")); } Dataset dstDs = srcDrv.CreateCopy(testPath, dswarp, 0, options, null, null); dstDs.FlushCache(); #endregion #region Create PNG string file_name = Path.GetFileNameWithoutExtension(inPutFile.Name) + "_kml.png"; string pngPath = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name); Band band1 = dstDs.GetRasterBand(band); //특정 벤드 가져오기 int startX = 0; int startY = 0; int width = band1.XSize; int height = band1.YSize; double[] geot = new double[6]; dstDs.GetGeoTransform(geot); double Xp = geot[0] + width * geot[1] + height * geot[2]; //우하단 double Yp = geot[3] + width * geot[4] + height * geot[5]; //우하단 north = geot[3]; //북 west = geot[0]; //서 south = Yp; //남 east = Xp; //동 int nBandSpace = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8; int nPixelSpace = nBandSpace * dataset.RasterCount; int nLineSpace = nPixelSpace * width; double[] buffer = new double[width * height]; CPLErr d = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0); double[] minmax = new double[2]; band1.ComputeRasterMinMax(minmax, 0); Bitmap bitmap = new Bitmap(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double value = buffer[x + y * width]; if (!Double.IsNaN(value)) { if (value >= minmax[0] && value <= minmax[1] && value != 0) { double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]); Color newColor = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue)); bitmap.SetPixel(x, y, newColor); } else { Color newColor = Color.FromArgb(0, 0, 0, 0); bitmap.SetPixel(x, y, newColor); } } } } bitmap.Save(pngPath, System.Drawing.Imaging.ImageFormat.Png); #endregion #region Create KML StreamWriter sw = new StreamWriter(outPut); sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); sw.WriteLine("<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd\">"); sw.WriteLine("<Document id=\"radar\">"); sw.WriteLine("\t<name>" + inPutFile.Name + "</name>"); sw.WriteLine("\t<Snippet></Snippet>"); sw.WriteLine("\t<GroundOverlay id=\"0\">"); sw.WriteLine("\t\t<Snippet></Snippet>"); sw.WriteLine("\t\t<drawOrder>1000</drawOrder>"); sw.WriteLine("\t\t<name>" + inPutFile.Name + "</name>"); sw.WriteLine("\t\t<Icon>\r\t\t\t<href>" + file_name + "</href>\r\t\t\t<viewBoundScale>1.0</viewBoundScale>\r\t\t</Icon>"); sw.WriteLine("\t\t<LatLonBox>"); sw.WriteLine("\t\t\t<north>" + north.ToString() + "</north>"); //북 sw.WriteLine("\t\t\t<south>" + south.ToString() + "</south>"); //남 sw.WriteLine("\t\t\t<east>" + east.ToString() + "</east>"); //동 sw.WriteLine("\t\t\t<west>" + west.ToString() + "</west>"); //서 sw.WriteLine("\t\t\t<rotation>0</rotation>"); //회전 sw.WriteLine("\t\t</LatLonBox>"); sw.WriteLine("\t</GroundOverlay>"); sw.WriteLine("</Document>"); sw.WriteLine("</kml>"); sw.Flush(); sw.Close(); sw.Dispose(); #endregion dataset.Dispose(); bitmap.Dispose(); dstDs.Dispose(); srcDrv.Dispose(); dswarp.Dispose(); File.Delete(testPath); } catch (Exception e) { return(false); } return(true); }
public bool TiffToJpg(string inPut, string outPut, int band = 1) { FileInfo inPutFile = new FileInfo(inPut); //입력 파일이 없다면 종료 if (!inPutFile.Exists) { return(false); } else { //입력 파일이 tif / tiff 파일이 아니라면 종료 if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff") { return(false); } } try { #region Create Jpg Gdal.AllRegister(); Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly); Band band1 = dataset.GetRasterBand(band); //특정 벤드 가져오기 int width = band1.XSize; int height = band1.YSize; int startX = 0; int startY = 0; int nBandSpace = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8; int nPixelSpace = nBandSpace * dataset.RasterCount; int nLineSpace = nPixelSpace * width; double[] buffer = new double[width * height]; CPLErr d = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0); double[] minmax = new double[2]; band1.ComputeRasterMinMax(minmax, 0); Bitmap bitmap = new Bitmap(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double value = buffer[x + y * width]; if (!Double.IsNaN(value)) { if (value >= minmax[0] && value <= minmax[1] && value != 0) { double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]); Color newColor = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue)); bitmap.SetPixel(x, y, newColor); } else { Color newColor = Color.FromArgb(0, 0, 0, 0); bitmap.SetPixel(x, y, newColor); } } } } bitmap.Save(outPut, System.Drawing.Imaging.ImageFormat.Jpeg); dataset.Dispose(); bitmap.Dispose(); #endregion } catch (Exception e) { return(false); } return(true); }
public bool ChangeProjectionByUTM(string inPut, string outPut, int band = 1) { FileInfo inPutFile = new FileInfo(inPut); bool isExtif = false; bool isExtiff = false; //입력 파일이 없다면 종료 if (!inPutFile.Exists) { return(false); } else { //입력 파일이 tif / tiff 파일이 아니라면 종료 if (inPutFile.Extension != ".tif" && inPutFile.Extension != ".tiff") { return(false); } if (inPutFile.Extension == ".tif") { isExtif = true; } if (inPutFile.Extension == ".tiff") { isExtiff = true; } } Gdal.AllRegister(); try { #region Change projection string strWorldSinusoidal = "PROJCS[\"World_Sinusoidal\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.0174532925199433],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Sinusoidal\"],PARAMETER[\"longitude_of_center\",0],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]]]"; string t_srs_wkt = "GEOGCS[\"WGS84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS84\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"degree\",0.01745329251994328]]"; Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly); dataset.SetProjection(strWorldSinusoidal); string s_srs_wkt = dataset.GetProjectionRef(); Dataset dswarp = Gdal.AutoCreateWarpedVRT(dataset, s_srs_wkt, t_srs_wkt, ResampleAlg.GRA_NearestNeighbour, 0); string[] options = null; OSGeo.GDAL.Driver srcDrv = Gdal.GetDriverByName("GTiff"); FileInfo outPutFile = new FileInfo(outPut); string testPath = string.Empty; if (isExtif) { testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tif", ".png")); } else if (isExtiff) { testPath = string.Format("{0}\\test_Png_{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".tiff", ".png")); } Dataset dstDs = srcDrv.CreateCopy(testPath, dswarp, 0, options, null, null); #endregion #region Create PNG string file_name = Path.GetFileNameWithoutExtension(inPutFile.Name) + ".png"; //string pngPath = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name); _strPngFile = string.Format("{0}\\{1}", outPutFile.DirectoryName, file_name); Band band1 = dstDs.GetRasterBand(band); //특정 벤드 가져오기 int startX = 0; int startY = 0; int width = band1.XSize; int height = band1.YSize; int nBandSpace = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8; int nPixelSpace = nBandSpace * dataset.RasterCount; int nLineSpace = nPixelSpace * width; double[] buffer = new double[width * height]; CPLErr d = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0); double[] minmax = new double[2]; band1.ComputeRasterMinMax(minmax, 0); Bitmap bitmap = new Bitmap(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double value = buffer[x + y * width]; if (!Double.IsNaN(value)) { if (value >= minmax[0] && value <= minmax[1] && value != 0) { double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]); Color newColor = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue)); bitmap.SetPixel(x, y, newColor); } else { Color newColor = Color.FromArgb(0, 0, 0, 0); bitmap.SetPixel(x, y, newColor); } } } } bitmap.Save(_strPngFile, System.Drawing.Imaging.ImageFormat.Png); #endregion #region Create a GeoTiff double north = 36.16465526448886; //북 double south = 35.97362616042732; //남 double east = 127.5672085281825; //동 double west = 127.3435070025512; //서 CheckGeoTransform(ref north, ref south, ref east, ref west, inPutFile); double[] newGeot = CalcGeoTransform(dstDs, north, south, east, west); OSGeo.GDAL.Driver driver = Gdal.GetDriverByName("GTiff"); Dataset oldDataSet = Gdal.Open(_strPngFile, Access.GA_ReadOnly); Dataset newDataSet = srcDrv.CreateCopy(outPut, oldDataSet, 0, null, null, null); newDataSet.SetProjection(dswarp.GetProjectionRef()); newDataSet.SetGeoTransform(newGeot); #endregion oldDataSet.Dispose(); newDataSet.Dispose(); driver.Dispose(); dataset.Dispose(); bitmap.Dispose(); dstDs.Dispose(); srcDrv.Dispose(); dswarp.Dispose(); File.Delete(testPath); //File.Delete(pngPath); } catch (Exception e) { return(false); } return(true); }
public bool ImgToGeoTiff(string inPut, string outPut, int band = 1) { FileInfo inPutFile = new FileInfo(inPut); //입력 파일이 없다면 종료 if (!inPutFile.Exists) { return(false); } else { //입력 파일이 img 파일이 아니라면 종료 if (inPutFile.Extension != ".img") { return(false); } } try { #region Create Tiff Gdal.AllRegister(); Dataset dataset = Gdal.Open(inPut, Access.GA_ReadOnly); Band band1 = dataset.GetRasterBand(band); //특정 벤드 가져오기 int width = band1.XSize; int height = band1.YSize; int startX = 0; int startY = 0; int nBandSpace = Gdal.GetDataTypeSize(DataType.GDT_Byte) / 8; int nPixelSpace = nBandSpace * dataset.RasterCount; int nLineSpace = nPixelSpace * width; double[] buffer = new double[width * height]; CPLErr d = band1.ReadRaster(startX, startY, width, height, buffer, width, height, 0, 0); double[] minmax = new double[2]; band1.ComputeRasterMinMax(minmax, 0); #region 복사할 이미지 생성 Bitmap bitmap = new Bitmap(width, height); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double value = buffer[x + y * width]; if (!Double.IsNaN(value)) { if (value >= minmax[0] && value <= minmax[1] && value != 0) { double colorValue = (value - minmax[0]) * 255 / (minmax[1] - minmax[0]); Color newColor = Color.FromArgb(Convert.ToInt32(colorValue), Convert.ToInt32(colorValue), Convert.ToInt32(colorValue)); bitmap.SetPixel(x, y, newColor); } else { Color newColor = Color.FromArgb(0, 0, 0, 0); bitmap.SetPixel(x, y, newColor); } } } } FileInfo outPutFile = new FileInfo(outPut); string pngPath = string.Format("{0}\\{1}", outPutFile.DirectoryName, inPutFile.Name.Replace(".img", ".png")); bitmap.Save(pngPath, System.Drawing.Imaging.ImageFormat.Png); #endregion string[] options = null; OSGeo.GDAL.Driver srcDrv = Gdal.GetDriverByName("GTiff"); Dataset srcDs = Gdal.Open(pngPath, Access.GA_ReadOnly); Dataset dstDs = srcDrv.CreateCopy(outPut, srcDs, 0, options, null, null); dstDs.SetProjection(dataset.GetProjection()); double[] geot = new double[6]; dataset.GetGeoTransform(geot); dstDs.SetGeoTransform(geot); dstDs.FlushCache(); dstDs.Dispose(); srcDs.Dispose(); srcDrv.Dispose(); bitmap.Dispose(); File.Delete(pngPath); #endregion } catch (Exception e) { return(false); } return(true); }
/// <summary> /// 瓦片地图拼接函数 /// 百度地图和高德地图瓦片地图组织形式不一样,用maptype加以区别 /// </summary> /// <param name="folder_list">文件夹列表</param> /// <param name="savepath">保存路径</param> /// <param name="maptype">0为百度地图,1为高德地图</param> WebApiResult <string> ParallelWriteImage(DirectoryInfo[] folder_list, String savepath, int maptype, string crstype, int maxSize) { FileInfo[] file = new FileInfo[] { }; foreach (var folder in folder_list) { FileInfo[] a = GetFileList(folder); file = JoinArray(file, a); } List <List <FileInfo> > file_list_blocks = new List <List <FileInfo> >(); deSplice(file, maxSize, ref file_list_blocks); var count = file_list_blocks.Count; //计算Total并更新 threadlog.Total = file_list_blocks.Count; new Log <BaiduTileSplicingResult>(threadlog); log.Count = threadlog.Total; new Log <BaiduTileSplicingResult>(log); //利用GDAL创建结果影像,并写入瓦片数据 Gdal.AllRegister(); //驱动注册 Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //中文路径支持 Driver pDriver = Gdal.GetDriverByName("GTIFF"); int num = 0; //分块拼接影像 foreach (var file_list_block in file_list_blocks) { if (num < current) { num++; continue; } //if (num == 6) Pause<BaiduTileSplicingResult>(this.Result_gaode.GUID); if (maptype == 0) { if (Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_baidu.GUID).IsPaused) { threadlog.Current = current; threadlog.Status = "暂停"; threadlog.TStatus = 4; threadlog.IsPaused = true; new Log <BaiduTileSplicingResult>(threadlog); log.Status = "未完成"; log.Current = current; new Log <BaiduTileSplicingResult>(log); return(null); } } else { if (Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_gaode.GUID).IsPaused) { threadlog.Current = current; threadlog.Status = "暂停"; threadlog.TStatus = 4; threadlog.IsPaused = true; new Log <BaiduTileSplicingResult>(threadlog); log.Status = "未完成"; log.Current = current; new Log <BaiduTileSplicingResult>(log); return(null); } } FileInfo[] file_list_array = file_list_block.ToArray <FileInfo>(); if (file_list_array.Length > 1) { //获取分块的坐标信息和范围信息 List <Point> TilePoints = GetTileCoor(file_list_array); Tuple <int, int, int, int> TileBoundary = GetBoundary(TilePoints); //定义存储文件名 string level = file_list_block[0].DirectoryName.Substring(0, file_list_block[0].DirectoryName.LastIndexOf("\\")).Split('$')[0]; level = level.Substring(level.LastIndexOf("\\")); string savedir = savepath + level; //判断存储路径是否存在 if (!Directory.Exists(savedir)) { Directory.CreateDirectory(savedir); } string dstPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tif"; if (File.Exists(dstPath)) { continue; } string tfwPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tfw"; if (File.Exists(tfwPath)) { continue; } //计算图像的宽度和高度,定义图像的Dataset int bufWidth = (TileBoundary.Item3 - TileBoundary.Item1 + 1) * 256; int bufHeight = (TileBoundary.Item4 - TileBoundary.Item2 + 1) * 256; Dataset dstDataset = pDriver.Create(dstPath, bufWidth, bufHeight, 3, DataType.GDT_Byte, new String[] { "BIGTIFF=IF_NEEDED" }); //生成.tfw文件 StreamWriter writer = new StreamWriter(new FileStream(tfwPath, FileMode.Create, FileAccess.Write), Encoding.ASCII); if (maptype == 0) { int z = int.Parse(level.Substring(1)); //计算瓦片地图左上角墨卡托坐标 double mcx = TileBoundary.Item1 * 256 * Math.Pow(2, (18 - z)); double mcy = (TileBoundary.Item4 + 1) * 256 * Math.Pow(2, (18 - z)); double sizex = 256 * Math.Pow(2, (18 - z)); double sizey = sizex; if (crstype == "BD09") { var F = CoordTransferHelper.Mercator2LatLng(new PointF((float)mcx, (float)mcy)); mcx = F.Lat; mcy = F.Lng; double r1 = (TileBoundary.Item3 + 1) * 256 * Math.Pow(2, (18 - z)); double r2 = TileBoundary.Item2 * 256 * Math.Pow(2, (18 - z)); F = CoordTransferHelper.Mercator2LatLng(new PointF((float)r1, (float)r2)); sizex = Math.Abs(mcx - F.Lat) / (TileBoundary.Item3 - TileBoundary.Item1 + 1); sizey = Math.Abs(mcy - F.Lng) / (TileBoundary.Item4 - TileBoundary.Item2 + 1); } writer.WriteLine(sizex); writer.WriteLine(0.000000); writer.WriteLine(0.000000); writer.WriteLine(-1 * sizey); writer.WriteLine(mcx); writer.WriteLine(mcy); } if (maptype == 1) { int z = int.Parse(level.Substring(1)); Point TileP = new Point(TileBoundary.Item1, TileBoundary.Item2); Point PixelP = new Point(0, 0); var P = CoordTransferHelper.PixelXY2LatLng(TileP, PixelP, z); double mcx = P.Lat; double mcy = P.Lng; P = CoordTransferHelper.PixelXY2LatLng(new Point(TileBoundary.Item3, TileBoundary.Item4), new Point(256, 256), z); double sizex = Math.Abs(mcx - P.Lat) / (TileBoundary.Item3 - TileBoundary.Item1 + 1); double sizey = Math.Abs(mcy - P.Lng) / (TileBoundary.Item4 - TileBoundary.Item2 + 1); writer.WriteLine(sizex); writer.WriteLine(0.000000); writer.WriteLine(0.000000); writer.WriteLine(sizey); writer.WriteLine(mcx); writer.WriteLine(mcy); } writer.Close(); //遍历分块列表中所有影像,读取瓦片图像信息写入分块影像 for (int i = 0; i < file_list_array.Length; i++) { //打开瓦片地图,获取瓦片地图的宽度、高度、波段、位数信息 Dataset img = Gdal.Open(file_list_array[i].FullName, Access.GA_ReadOnly); int Width = img.RasterXSize; int Height = img.RasterYSize; int BandNum = img.RasterCount; int Depth = Gdal.GetDataTypeSize(img.GetRasterBand(1).DataType); //读取瓦片地图的数据信息 Byte[] buf = new Byte[Width * Height * BandNum]; CPLErr err = img.ReadRaster(0, 0, Width, Height, buf, Width, Height, BandNum, null, 0, 0, 0); if (err == CPLErr.CE_Failure) { string message = string.Format("{0}图像读取失败!", file_list_array[i].Name); return(new WebApiResult <string>() { success = 1, msg = message }); } //获取瓦片地图在拼接影像中的起始坐标信息 int OrgX = -9999, OrgY = -9999; if (maptype == 0) { OrgX = (TilePoints[i].X - TileBoundary.Item1) * 256; OrgY = (TileBoundary.Item4 - TilePoints[i].Y) * 256; } else if (maptype == 1) { OrgX = (TilePoints[i].X - TileBoundary.Item1) * 256; OrgY = (TilePoints[i].Y - TileBoundary.Item2) * 256; } if (OrgX == -9999 || OrgY == -9999) { return new WebApiResult <string>() { success = 1, msg = "坐标错误" } } ;; err = dstDataset.WriteRaster(OrgX, OrgY, Width, Height, buf, Width, Height, BandNum, null, 0, 0, 0); if (err == CPLErr.CE_Failure) { string message = string.Format("结果图像{0}输出数据失败!", file_list_block.First <FileInfo>().Name + "_" + file_list_block.Last <FileInfo>().Name + ".tif"); return(new WebApiResult <string>() { success = 1, msg = message }); } img.Dispose(); } dstDataset.Dispose(); } else { //定义存储文件名 string level = file_list_block[0].DirectoryName.Substring(0, file_list_block[0].DirectoryName.LastIndexOf("\\")).Split('_')[0]; level = level.Substring(level.LastIndexOf("\\")); string savedir = savepath + level; //判断存储路径是否存在 if (!Directory.Exists(savedir)) { Directory.CreateDirectory(savedir); } string dstPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tif"; if (File.Exists(dstPath)) { continue; } File.Copy(file_list_array[0].FullName.ToString(), dstPath); } current++; num++; if (maptype == 0) { threadlog = Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_baidu.GUID); } else { threadlog = Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_gaode.GUID); } threadlog.Current = current; new Log <BaiduTileSplicingResult>(threadlog); } pDriver.Deregister(); Gdal.GDALDestroyDriverManager(); return(new WebApiResult <string>() { success = 1, msg = "瓦片拼接完成!" }); }