Example #1
0
        private void ReadPaletteBuffered()
        {
            ColorTable ct = _red.GetRasterColorTable();

            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }
            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException(String.Format("Only RGB palette interpretation is currently supported by this plug-in, {0} is not supported.", ct.GetPaletteInterpretation()));
            }
            int width  = Width;
            int height = Height;

            byte[] r = new byte[width * height];
            _red.ReadRaster(0, 0, width, height, r, width, height, 0, 0);

            _image = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            BitmapData bData = _image.LockBits(new Rectangle(0, 0, width, height),
                                               ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            Stride = bData.Stride;
            _image.UnlockBits(bData);

            const int bpp    = 4;
            int       stride = Stride;

            byte[]   vals       = new byte[width * height * 4];
            byte[][] colorTable = new byte[ct.GetCount()][];
            for (int i = 0; i < ct.GetCount(); i++)
            {
                ColorEntry ce = ct.GetColorEntry(i);
                colorTable[i] = new[]
                {
                    (byte)ce.c3, (byte)ce.c2, (byte)ce.c1,
                    (byte)ce.c4
                };
            }
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    Array.Copy(colorTable[r[col + row * width]], 0, vals,
                               row * stride + col * bpp, 4);
                }
            }
            Values = vals;
            CopyValuesToBitmap();
        }
Example #2
0
        public override System.Drawing.Color[] CategoryColors()
        {
            System.Drawing.Color[] Colors = null;
            ColorTable             table  = GetColorTable();

            if (table != null)
            {
                int ColorCount = table.GetCount();
                if (ColorCount > 0)
                {
                    Colors = new System.Drawing.Color[ColorCount];
                    for (int ColorIndex = 0; ColorIndex < ColorCount; ColorIndex += 1)
                    {
                        Colors[ColorIndex] = System.Drawing.Color.DimGray;
                        ColorEntry entry = table.GetColorEntry(ColorIndex);
                        switch (table.GetPaletteInterpretation())
                        {
                        case PaletteInterp.GPI_RGB: Colors[ColorIndex] = System.Drawing.Color.FromArgb(entry.c4, entry.c1, entry.c2, entry.c3); break;

                        case PaletteInterp.GPI_Gray: Colors[ColorIndex] = System.Drawing.Color.FromArgb(255, entry.c1, entry.c1, entry.c1); break;
                            //TODO: do any files use these types?
                            //case PaletteInterp.GPI_HLS
                            //case PaletteInterp.GPI_CMYK
                        }
                    }
                }
            }
            return(Colors);
        }
Example #3
0
        private static void SetColorPalette(Dataset ds, Bitmap bitmap)
        {
            List <OSGeo.GDAL.ColorInterp> interps = GetRasterColorInterps(ds);
            int paletteIndex = interps.IndexOf(OSGeo.GDAL.ColorInterp.GCI_PaletteIndex);
            int grayIndex    = interps.IndexOf(OSGeo.GDAL.ColorInterp.GCI_GrayIndex);

            if (paletteIndex > -1)
            {
                ColorTable ct   = ds.GetRasterBand(paletteIndex + 1).GetRasterColorTable();
                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 if (grayIndex > -1)
            {
                ColorPalette pal = bitmap.Palette;
                for (int i = 0; i < 256; i++)
                {
                    pal.Entries[i] = Color.FromArgb(255, i, i, i);
                }
                bitmap.Palette = pal;
            }
        }
Example #4
0
        private static void WritePaletteBuffered(Bitmap value, int xOffset, int yOffset, Band first)
        {
            ColorTable ct = first.GetRasterColorTable();

            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }
            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException("Only RGB palette interpretation is currently supported by this " +
                                        " plug-in, " + ct.GetPaletteInterpretation() + " is not supported.");
            }
            int        width  = value.Width;
            int        height = value.Height;
            BitmapData bData  = value.LockBits(new Rectangle(0, 0, width, height),
                                               ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);

            byte[] r = new byte[stride * height];
            Marshal.Copy(bData.Scan0, r, 0, r.Length);
            value.UnlockBits(bData);
            byte[]   vals       = new byte[width * height];
            byte[][] colorTable = new byte[ct.GetCount()][];
            for (int i = 0; i < ct.GetCount(); i++)
            {
                ColorEntry ce = ct.GetColorEntry(i);
                colorTable[i] = new[]
                {
                    (byte)ce.c3, (byte)ce.c2, (byte)ce.c1,
                    (byte)ce.c4
                };
            }
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    vals[row * width + col] = MatchColor(r, row * stride + col * 4, colorTable);
                }
            }
            first.WriteRaster(xOffset, yOffset, width, height, vals, width, height, 0, 0);
        }
Example #5
0
        public static Bitmap LoadImage(string file)
        {
            lock (locker)
            {
                using (var ds = OSGeo.GDAL.Gdal.Open(file, OSGeo.GDAL.Access.GA_ReadOnly))
                {
                    // Get the GDAL Band objects from the Dataset
                    Band band = ds.GetRasterBand(1);
                    if (band == null)
                    {
                        return(null);
                    }
                    ColorTable ct = band.GetRasterColorTable();
                    // Create a Bitmap to store the GDAL image in
                    Bitmap bitmap = new Bitmap(ds.RasterXSize, ds.RasterYSize, PixelFormat.Format8bppIndexed);
                    // Obtaining the bitmap buffer
                    BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, ds.RasterXSize, ds.RasterYSize),
                                                            ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
                    try
                    {
                        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;
                        }

                        int    stride = bitmapData.Stride;
                        IntPtr buf    = bitmapData.Scan0;

                        band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buf, ds.RasterXSize, ds.RasterYSize,
                                        DataType.GDT_Byte, 1, stride);
                    }
                    finally
                    {
                        bitmap.UnlockBits(bitmapData);
                    }

                    return(bitmap);
                }
            }
        }
    private static void LoadBitmapDirect(Dataset ds, Bitmap bitmap, int xOff, int yOff, int width, int height, int imageWidth, int imageHeight, int iOverview)
    {
        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;
            IntPtr buf    = bitmapData.Scan0;

            ds.ReadRaster(xOff, yOff, width, height, buf, imageWidth, imageHeight, dataType,
                          channelCount, bandMap, pixelSpace, stride, 1);
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }
    }
Example #7
0
        /// <summary>
        /// This is only used in the palette indexed band type.
        /// </summary>
        public override IEnumerable <Color> GetColorPalette()
        {
            if (ColorPalette == null)
            {
                _dataset = Helpers.Open(Filename);
                Band         first  = _dataset.GetRasterBand(1);
                ColorTable   ct     = first.GetRasterColorTable();
                int          count  = ct.GetCount();
                List <Color> result = new List <Color>();
                for (int i = 0; i < count; i++)
                {
                    ColorEntry ce = ct.GetColorEntry(i);
                    result.Add(Color.FromArgb(ce.c4, ce.c1, ce.c2, ce.c3));
                }
                ColorPalette = result;
            }

            return(ColorPalette);
        }
Example #8
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            usage();
        }

        Console.WriteLine("");
        try
        {
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open(args[0], Access.GA_ReadOnly);

            if (ds == null)
            {
                Console.WriteLine("Can't open " + args[0]);
                Environment.Exit(-1);
            }

            Console.WriteLine("Raster dataset parameters:");
            Console.WriteLine("  Projection: " + ds.GetProjectionRef());
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */
            Driver drv = ds.GetDriver();

            if (drv == null)
            {
                Console.WriteLine("Can't get driver.");
                Environment.Exit(-1);
            }

            Console.WriteLine("Using driver " + drv.LongName);

            /* -------------------------------------------------------------------- */
            /*      Get metadata                                                    */
            /* -------------------------------------------------------------------- */
            string[] metadata = ds.GetMetadata("");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report "IMAGE_STRUCTURE" metadata.                              */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("IMAGE_STRUCTURE");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Image Structure Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report subdatasets.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("SUBDATASETS");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Subdatasets:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report geolocation.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("GEOLOCATION");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Geolocation:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report corners.                                                 */
            /* -------------------------------------------------------------------- */
            Console.WriteLine("Corner Coordinates:");
            Console.WriteLine("  Upper Left (" + GDALInfoGetPosition(ds, 0.0, 0.0) + ")");
            Console.WriteLine("  Lower Left (" + GDALInfoGetPosition(ds, 0.0, ds.RasterYSize) + ")");
            Console.WriteLine("  Upper Right (" + GDALInfoGetPosition(ds, ds.RasterXSize, 0.0) + ")");
            Console.WriteLine("  Lower Right (" + GDALInfoGetPosition(ds, ds.RasterXSize, ds.RasterYSize) + ")");
            Console.WriteLine("  Center (" + GDALInfoGetPosition(ds, ds.RasterXSize / 2, ds.RasterYSize / 2) + ")");
            Console.WriteLine("");

            /* -------------------------------------------------------------------- */
            /*      Report projection.                                              */
            /* -------------------------------------------------------------------- */
            string projection = ds.GetProjectionRef();
            if (projection != null)
            {
                SpatialReference srs = new SpatialReference(null);
                if (srs.ImportFromWkt(ref projection) == 0)
                {
                    string wkt;
                    srs.ExportToPrettyWkt(out wkt, 0);
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(wkt);
                }
                else
                {
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(projection);
                }
            }

            /* -------------------------------------------------------------------- */
            /*      Report GCPs.                                                    */
            /* -------------------------------------------------------------------- */
            if (ds.GetGCPCount() > 0)
            {
                Console.WriteLine("GCP Projection: ", ds.GetGCPProjection());
                GCP[] GCPs = ds.GetGCPs();
                for (int i = 0; i < ds.GetGCPCount(); i++)
                {
                    Console.WriteLine("GCP[" + i + "]: Id=" + GCPs[i].Id + ", Info=" + GCPs[i].Info);
                    Console.WriteLine("          (" + GCPs[i].GCPPixel + "," + GCPs[i].GCPLine + ") -> ("
                                      + GCPs[i].GCPX + "," + GCPs[i].GCPY + "," + GCPs[i].GCPZ + ")");
                    Console.WriteLine("");
                }
                Console.WriteLine("");

                double[] transform = new double[6];
                Gdal.GCPsToGeoTransform(GCPs, transform, 0);
                Console.WriteLine("GCP Equivalent geotransformation parameters: ", ds.GetGCPProjection());
                for (int i = 0; i < 6; i++)
                {
                    Console.WriteLine("t[" + i + "] = " + transform[i].ToString());
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Get raster band                                                 */
            /* -------------------------------------------------------------------- */
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++)
            {
                Band band = ds.GetRasterBand(iBand);
                Console.WriteLine("Band " + iBand + " :");
                Console.WriteLine("   DataType: " + Gdal.GetDataTypeName(band.DataType));
                Console.WriteLine("   ColorInterpretation: " + Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()));
                ColorTable ct = band.GetRasterColorTable();
                if (ct != null)
                {
                    Console.WriteLine("   Band has a color table with " + ct.GetCount() + " entries.");
                }

                Console.WriteLine("   Description: " + band.GetDescription());
                Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
                int BlockXSize, BlockYSize;
                band.GetBlockSize(out BlockXSize, out BlockYSize);
                Console.WriteLine("   BlockSize (" + BlockXSize + "," + BlockYSize + ")");
                double val;
                int    hasval;
                band.GetMinimum(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Minimum: " + val.ToString());
                }
                band.GetMaximum(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Maximum: " + val.ToString());
                }
                band.GetNoDataValue(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   NoDataValue: " + val.ToString());
                }
                band.GetOffset(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Offset: " + val.ToString());
                }
                band.GetScale(out val, out hasval);
                if (hasval != 0)
                {
                    Console.WriteLine("   Scale: " + val.ToString());
                }

                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                {
                    Band over = band.GetOverview(iOver);
                    Console.WriteLine("      OverView " + iOver + " :");
                    Console.WriteLine("         DataType: " + over.DataType);
                    Console.WriteLine("         Size (" + over.XSize + "," + over.YSize + ")");
                    Console.WriteLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
                }
            }

            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }
Example #9
0
        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);
        }
Example #10
0
    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);
    }
Example #11
0
        public static Bitmap LoadImage(string file)
        {
            lock (locker)
            {
                using (var ds = OSGeo.GDAL.Gdal.Open(file, OSGeo.GDAL.Access.GA_ReadOnly))
                {
                    // 8bit geotiff - single band
                    if (ds.RasterCount == 1)
                    {
                        Band band = ds.GetRasterBand(1);
                        if (band == null)
                        {
                            return(null);
                        }

                        ColorTable ct = band.GetRasterColorTable();

                        PixelFormat format = PixelFormat.Format8bppIndexed;

                        // Create a Bitmap to store the GDAL image in
                        Bitmap bitmap = new Bitmap(ds.RasterXSize, ds.RasterYSize, format);

                        // Obtaining the bitmap buffer
                        BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, ds.RasterXSize, ds.RasterYSize),
                                                                ImageLockMode.ReadWrite, format);
                        try
                        {
                            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
                            {
                            }

                            int    stride = bitmapData.Stride;
                            IntPtr buf    = bitmapData.Scan0;

                            band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buf, ds.RasterXSize, ds.RasterYSize,
                                            DataType.GDT_Byte, 1, stride);
                        }
                        finally
                        {
                            bitmap.UnlockBits(bitmapData);
                        }


                        return(bitmap);
                    }

                    {
                        Bitmap bitmap = new Bitmap(ds.RasterXSize, ds.RasterYSize, PixelFormat.Format32bppArgb);
                        if (ds.RasterCount == 3)
                        {
                            // when we load a 24bit bitmap, we need to set the alpha channel else we get nothing
                            using (var tmp = Graphics.FromImage(bitmap))
                            {
                                tmp.Clear(Color.White);
                            }
                        }

                        for (int a = 1; a <= ds.RasterCount; a++)
                        {
                            // Get the GDAL Band objects from the Dataset
                            Band band = ds.GetRasterBand(a);
                            if (band == null)
                            {
                                return(null);
                            }

                            var cint = band.GetColorInterpretation();


                            // Obtaining the bitmap buffer
                            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, ds.RasterXSize, ds.RasterYSize),
                                                                    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                            try
                            {
                                int    stride = bitmapData.Stride;
                                IntPtr buf    = bitmapData.Scan0;
                                var    buffer = new byte[ds.RasterXSize * ds.RasterYSize];

                                band.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buffer, ds.RasterXSize,
                                                ds.RasterYSize, 1, ds.RasterXSize);

                                int c = 0;
                                if (cint == ColorInterp.GCI_AlphaBand)
                                {
                                    foreach (var b in buffer)
                                    {
                                        Marshal.WriteByte(buf, 3 + c * 4, (byte)b);
                                        c++;
                                    }
                                }
                                else if (cint == ColorInterp.GCI_RedBand)
                                {
                                    foreach (var b in buffer)
                                    {
                                        Marshal.WriteByte(buf, 2 + c * 4, (byte)b);
                                        c++;
                                    }
                                }
                                else if (cint == ColorInterp.GCI_GreenBand)
                                {
                                    foreach (var b in buffer)
                                    {
                                        Marshal.WriteByte(buf, 1 + c * 4, (byte)b);
                                        c++;
                                    }
                                }
                                else if (cint == ColorInterp.GCI_BlueBand)
                                {
                                    foreach (var b in buffer)
                                    {
                                        Marshal.WriteByte(buf, 0 + c * 4, (byte)b);
                                        c++;
                                    }
                                }
                                else
                                {
                                }
                            }
                            finally
                            {
                                bitmap.UnlockBits(bitmapData);
                            }
                        }

                        //bitmap.Save("gdal.png", ImageFormat.Png);
                        return(bitmap);
                    }
                }
            }

            return(null);
        }
Example #12
0
        private Bitmap ReadPaletteBuffered(int xOffset, int yOffset, int xSize, int ySize, Band first)
        {
            ColorTable ct = first.GetRasterColorTable();

            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }

            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException("Only RGB palette interpretation is currently supported by this " + " plug-in, " + ct.GetPaletteInterpretation() + " is not supported.");
            }

            Band firstO;
            bool disposeO = false;

            if (_overview >= 0 && first.GetOverviewCount() > 0)
            {
                firstO   = first.GetOverview(_overview);
                disposeO = true;
            }
            else
            {
                firstO = first;
            }

            int width, height;

            NormalizeSizeToBand(xOffset, yOffset, xSize, ySize, firstO, out width, out height);
            byte[] r = new byte[width * height];

            firstO.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0);
            if (disposeO)
            {
                firstO.Dispose();
            }

            Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            BitmapData bData  = result.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            int        stride = Math.Abs(bData.Stride);

            const int Bpp = 4;

            byte[]   vals       = new byte[stride * height];
            byte[][] colorTable = new byte[ct.GetCount()][];
            for (int i = 0; i < ct.GetCount(); i++)
            {
                ColorEntry ce = ct.GetColorEntry(i);
                colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 };
            }

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    Array.Copy(colorTable[r[col + (row * width)]], 0, vals, (row * stride) + (col * Bpp), 4);
                }
            }

            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            result.UnlockBits(bData);
            return(result);
        }
Example #13
0
        private Bitmap ReadPaletteBuffered(int xOffset, int yOffset, int xSize, int ySize)
        {
            ColorTable ct = _band.GetRasterColorTable();

            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }

            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException("Only RGB palette interpretation is currently supported by this " + " plug-in, " + ct.GetPaletteInterpretation() + " is not supported.");
            }

            int count = ct.GetCount();

            byte[][] colorTable = new byte[ct.GetCount()][];
            for (int i = 0; i < count; i++)
            {
                using (ColorEntry ce = ct.GetColorEntry(i))
                {
                    colorTable[i] = new[] { (byte)ce.c4, (byte)ce.c1, (byte)ce.c2, (byte)ce.c3 };
                }
            }
            ct.Dispose();

            Band firstBand;
            bool disposeBand = false;

            if (_overview >= 0 && _overviewCount > 0)
            {
                firstBand   = _band.GetOverview(_overview);
                disposeBand = true;
            }
            else
            {
                firstBand = _band;
            }
            GdalExtensions.NormalizeSizeToBand(firstBand.XSize, firstBand.YSize, xOffset, yOffset, xSize, ySize, out int width, out int height);
            byte[] indexBuffer = firstBand.ReadBand(xOffset, yOffset, width, height, width, height);
            if (disposeBand)
            {
                firstBand.Dispose();
            }
            byte[] rBuffer = new byte[indexBuffer.Length];
            byte[] gBuffer = new byte[indexBuffer.Length];
            byte[] bBuffer = new byte[indexBuffer.Length];
            byte[] aBuffer = new byte[indexBuffer.Length];
            for (int i = 0; i < indexBuffer.Length; i++)
            {
                int index = indexBuffer[i];
                aBuffer[i] = colorTable[index][0];
                rBuffer[i] = colorTable[index][1];
                gBuffer[i] = colorTable[index][2];
                bBuffer[i] = colorTable[index][3];
            }
            Bitmap result = GdalExtensions.GetBitmap(width, height, rBuffer, gBuffer, gBuffer, aBuffer, NoDataValue);

            rBuffer = null;
            gBuffer = null;
            bBuffer = null;
            aBuffer = null;
            return(result);
        }
Example #14
0
        public static String GetInfo(Dataset ds)
        {
            StringBuilder builder = new StringBuilder();

            try
            {
                if (ds == null)
                {
                    return("");
                }

                //builder.AppendLine("  Projection: " + ds.GetProjectionRef());


                /* -------------------------------------------------------------------- */
                /*      Get driver                                                      */
                /* -------------------------------------------------------------------- */
                Driver drv = ds.GetDriver();

                if (drv == null)
                {
                    return("Can't get driver.");
                }

                builder.AppendLine("Driver " + drv.ShortName + "/" + drv.LongName);

                string[] fileList = ds.GetFileList();
                if (fileList.Length > 0)
                {
                    builder.AppendLine("Files:");
                    for (int iMeta = 0; iMeta < fileList.Length; iMeta++)
                    {
                        byte[] bytes    = Encoding.Default.GetBytes(fileList[iMeta]);
                        String fileName = Encoding.UTF8.GetString(bytes);
                        builder.AppendLine("      " + fileName);
                    }
                }
                builder.AppendLine("BandCount: " + ds.RasterCount);
                builder.AppendLine("Size is " + ds.RasterXSize + ", " + ds.RasterYSize);

                /* -------------------------------------------------------------------- */
                /*      Report projection.                                              */
                /* -------------------------------------------------------------------- */
                string projection = ds.GetProjectionRef();
                if (projection != null)
                {
                    SpatialReference srs = new SpatialReference(null);
                    if (srs.ImportFromWkt(ref projection) == 0)
                    {
                        string wkt;
                        srs.ExportToPrettyWkt(out wkt, 0);
                        builder.AppendLine("Coordinate System is:");
                        builder.AppendLine(wkt);
                    }
                    else
                    {
                        builder.AppendLine("Coordinate System is:");
                        builder.AppendLine(projection);
                    }
                }

                /* -------------------------------------------------------------------- */
                /*      Report GCPs.                                                    */
                /* -------------------------------------------------------------------- */
                if (ds.GetGCPCount() > 0)
                {
                    builder.AppendLine("GCP Projection: " + ds.GetGCPProjection());
                    GCP[] GCPs = ds.GetGCPs();
                    for (int i = 0; i < ds.GetGCPCount(); i++)
                    {
                        builder.AppendLine("GCP[" + i + "]: Id=" + GCPs[i].Id + ", Info=" + GCPs[i].Info);
                        builder.AppendLine("          (" + GCPs[i].GCPPixel + "," + GCPs[i].GCPLine + ") -> ("
                                           + GCPs[i].GCPX + "," + GCPs[i].GCPY + "," + GCPs[i].GCPZ + ")");
                        builder.AppendLine("");
                    }
                    builder.AppendLine("");

                    double[] geotransform = new double[6];
                    Gdal.GCPsToGeoTransform(GCPs, geotransform, 0);
                    builder.AppendLine("GCP Equivalent geotransformation parameters: " + ds.GetGCPProjection());
                    for (int i = 0; i < 6; i++)
                    {
                        builder.AppendLine("t[" + i + "] = " + geotransform[i].ToString());
                    }
                    builder.AppendLine("");
                }

                double[] transform = GetGeoTransform(ds);
                builder.AppendLine("Origin = (" + GDALInfoGetPosition(transform, 0.0, 0.0) + ")");
                builder.AppendLine("Pixel Size = (" + transform[1].ToString("f16") + "," + transform[5].ToString("f16") + ")");

                /* -------------------------------------------------------------------- */
                /*      Get metadata                                                    */
                /* -------------------------------------------------------------------- */
                string[] metadata = ds.GetMetadata("");
                if (metadata.Length > 0)
                {
                    builder.AppendLine("Metadata:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        builder.AppendLine("  " + metadata[iMeta]);
                    }
                }

                /* -------------------------------------------------------------------- */
                /*      Report "IMAGE_STRUCTURE" metadata.                              */
                /* -------------------------------------------------------------------- */
                metadata = ds.GetMetadata("IMAGE_STRUCTURE");
                if (metadata.Length > 0)
                {
                    builder.AppendLine("Image Structure Metadata:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        builder.AppendLine("  " + metadata[iMeta]);
                    }
                }

                /* -------------------------------------------------------------------- */
                /*      Report subdatasets.                                             */
                /* -------------------------------------------------------------------- */
                metadata = ds.GetMetadata("SUBDATASETS");
                if (metadata.Length > 0)
                {
                    builder.AppendLine("  Subdatasets:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        builder.AppendLine("    " + metadata[iMeta]);
                    }
                    builder.AppendLine("");
                }

                /* -------------------------------------------------------------------- */
                /*      Report geolocation.                                             */
                /* -------------------------------------------------------------------- */
                metadata = ds.GetMetadata("GEOLOCATION");
                if (metadata.Length > 0)
                {
                    builder.AppendLine("  Geolocation:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        builder.AppendLine("    " + metadata[iMeta]);
                    }
                    builder.AppendLine("");
                }

                /* -------------------------------------------------------------------- */
                /*      Report corners.                                                 */
                /* -------------------------------------------------------------------- */
                builder.AppendLine("Corner Coordinates:");
                builder.AppendLine("  Upper Left (" + GDALInfoGetPosition(transform, 0.0, 0.0) + ")");
                builder.AppendLine("  Lower Left (" + GDALInfoGetPosition(transform, 0.0, ds.RasterYSize) + ")");
                builder.AppendLine("  Upper Right (" + GDALInfoGetPosition(transform, ds.RasterXSize, 0.0) + ")");
                builder.AppendLine("  Lower Right (" + GDALInfoGetPosition(transform, ds.RasterXSize, ds.RasterYSize) + ")");
                builder.AppendLine("  Center (" + GDALInfoGetPosition(transform, ds.RasterXSize / 2, ds.RasterYSize / 2) + ")");
                builder.AppendLine("");



                /* -------------------------------------------------------------------- */
                /*      Get raster band                                                 */
                /* -------------------------------------------------------------------- */
                for (int iBand = 1; iBand <= ds.RasterCount; iBand++)
                {
                    Band band = ds.GetRasterBand(iBand);
                    int  blockXSize, blockYSize;
                    band.GetBlockSize(out blockXSize, out blockYSize);

                    builder.Append("Band ");
                    builder.Append(iBand);
                    builder.Append(" Block=");
                    builder.Append(blockXSize);
                    builder.Append("x");
                    builder.Append(blockYSize);
                    builder.Append(", Type=");
                    builder.Append(Gdal.GetDataTypeName(band.DataType));
                    builder.Append(", ColorInterp=");
                    builder.Append(Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()));

                    double val;
                    int    hasval;
                    band.GetMinimum(out val, out hasval);
                    if (hasval != 0)
                    {
                        builder.Append(", Minimum=" + val.ToString());
                    }
                    band.GetMaximum(out val, out hasval);
                    if (hasval != 0)
                    {
                        builder.Append(", Maximum=" + val.ToString());
                    }
                    band.GetNoDataValue(out val, out hasval);
                    if (hasval != 0)
                    {
                        builder.Append(", NoDataValue=" + val.ToString());
                    }
                    band.GetOffset(out val, out hasval);
                    if (hasval != 0)
                    {
                        builder.Append(", Offset=" + val.ToString());
                    }
                    band.GetScale(out val, out hasval);
                    if (hasval != 0)
                    {
                        builder.Append(", Scale=" + val.ToString());
                    }
                    builder.AppendLine("");

                    if (band.GetOverviewCount() > 0)
                    {
                        builder.Append(" OverViews: ");
                        for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                        {
                            Band over = band.GetOverview(iOver);
                            builder.Append(over.XSize + "x" + over.YSize + ", ");
                            // builder.AppendLine("         DataType: " + over.DataType);
                            // builder.AppendLine("         Size (" + over.XSize + "," + over.YSize + ")");
                            //builder.AppendLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
                        }
                        builder.AppendLine("");
                    }

                    ColorTable ct = band.GetRasterColorTable();
                    if (ct != null)
                    {
                        builder.AppendLine(" Band has a color table with " + ct.GetCount() + " entries.");
                    }

                    String des = band.GetDescription();
                    if (des != null && !String.IsNullOrWhiteSpace(des))
                    {
                        builder.AppendLine(" Description: " + band.GetDescription());
                    }
                }
            }
            catch (Exception e)
            {
                return("Application error: " + e.Message);
            }

            return(builder.ToString());
        }
Example #15
0
        private void getGdalinfo()
        {
            //================================================================
            // Initialize
            //================================================================
            reset();

            //================================================================
            // Get gdal info
            //================================================================
            try {
                //------------------------------------------------------------
                // Open dataset
                //------------------------------------------------------------
                m_tGdalDs = Gdal.Open(m_strGeoTiffPath, Access.GA_ReadOnly);

                if (m_tGdalDs == null)
                {
                    m_ctrlLogger.FatalFormat("Can't open {0}", m_strGeoTiffPath);
                    throw new ArgumentException("Parameter cannot be null", "original");
                }
                m_strGdalInfoTxt.AppendLine("GeoTIFF file path:");
                m_strGdalInfoTxt.AppendFormat("  {0}", m_strGeoTiffPath).AppendLine();
                m_strGdalInfoTxt.AppendLine("Raster dataset parameters:");
                m_strGdalInfoTxt.AppendFormat("  Projection: {0}",
                                              m_tGdalDs.GetProjectionRef()).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  RasterCount: {0}",
                                              m_tGdalDs.RasterCount).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  RasterSize ({0},{1})",
                                              m_tGdalDs.RasterXSize, m_tGdalDs.RasterYSize).AppendLine();

                //------------------------------------------------------------
                // Get driver
                //------------------------------------------------------------
                m_tGdalDriver = m_tGdalDs.GetDriver();

                if (m_tGdalDriver == null)
                {
                    m_ctrlLogger.Fatal("Can't get driver.");
                    throw new ArgumentException("Parameter cannot be null", "original");
                }

                m_strGdalInfoTxt.AppendFormat("Using driver {0}",
                                              m_tGdalDriver.LongName).AppendLine();

                //------------------------------------------------------------
                // Get meta data
                //------------------------------------------------------------
                string[] metadata = m_tGdalDs.GetMetadata(string.Empty);
                if (metadata.Length > 0)
                {
                    m_strGdalInfoTxt.AppendLine("  Metadata:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        m_strGdalInfoTxt.AppendFormat("    {0}: {1}",
                                                      iMeta, metadata[iMeta]).AppendLine();
                    }
                    m_strGdalInfoTxt.AppendLine();
                }

                //------------------------------------------------------------
                // Report "IMAGE_STRUCTURE" metadata
                //------------------------------------------------------------
                metadata = m_tGdalDs.GetMetadata("IMAGE_STRUCTURE");
                if (metadata.Length > 0)
                {
                    m_strGdalInfoTxt.AppendLine("  Image Structure Metadata:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        m_strGdalInfoTxt.AppendFormat("    {0}: {1}",
                                                      iMeta, metadata[iMeta]).AppendLine();
                    }
                    m_strGdalInfoTxt.AppendLine();
                }

                //------------------------------------------------------------
                // Report subdatasets
                //------------------------------------------------------------
                metadata = m_tGdalDs.GetMetadata("SUBDATASETS");
                if (metadata.Length > 0)
                {
                    m_strGdalInfoTxt.AppendLine("  Subdatasets:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        m_strGdalInfoTxt.AppendFormat("    {0}: {1}",
                                                      iMeta, metadata[iMeta]).AppendLine();
                    }
                    m_strGdalInfoTxt.AppendLine();
                }

                //------------------------------------------------------------
                // Report geolocation
                //------------------------------------------------------------
                metadata = m_tGdalDs.GetMetadata("GEOLOCATION");
                if (metadata.Length > 0)
                {
                    m_strGdalInfoTxt.AppendLine("  Geolocation:");
                    for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                    {
                        m_strGdalInfoTxt.AppendFormat("    {0}: {1}",
                                                      iMeta, metadata[iMeta]).AppendLine();
                    }
                    m_strGdalInfoTxt.AppendLine();
                }

                //------------------------------------------------------------
                // Report corners
                //------------------------------------------------------------
                m_strGdalInfoTxt.AppendLine("Corner Coordinates:");
                m_strGdalInfoTxt.AppendFormat("  Upper Left ({0})",
                                              GDALInfoGetPosition(0.0, 0.0)).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  Lower Left ({0})",
                                              GDALInfoGetPosition(0.0, m_tGdalDs.RasterYSize)).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  Upper Right ({0})",
                                              GDALInfoGetPosition(m_tGdalDs.RasterXSize, 0.0)).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  Lower Right ({0})",
                                              GDALInfoGetPosition(m_tGdalDs.RasterXSize, m_tGdalDs.RasterYSize)).AppendLine();
                m_strGdalInfoTxt.AppendFormat("  Center ({0})",
                                              GDALInfoGetPosition(m_tGdalDs.RasterXSize / 2, m_tGdalDs.RasterYSize / 2)).AppendLine();
                m_strGdalInfoTxt.AppendLine();

                //------------------------------------------------------------
                // Report projection
                //------------------------------------------------------------
                string projection = m_tGdalDs.GetProjectionRef();
                if (projection != null)
                {
                    SpatialReference srs = new SpatialReference(null);
                    if (srs.ImportFromWkt(ref projection) == 0)
                    {
                        string wkt;
                        srs.ExportToPrettyWkt(out wkt, 0);
                        m_strGdalInfoTxt.AppendLine("Coordinate System is:");
                        m_strGdalInfoTxt.AppendLine(wkt);
                    }
                    else
                    {
                        m_strGdalInfoTxt.AppendLine("Coordinate System is:");
                        m_strGdalInfoTxt.AppendLine(projection);
                    }
                }

                //------------------------------------------------------------
                // Report GCPs
                //------------------------------------------------------------
                if (m_tGdalDs.GetGCPCount() > 0)
                {
                    m_strGdalInfoTxt.AppendFormat("GCP Projection: {0}",
                                                  m_tGdalDs.GetGCPProjection()).AppendLine();
                    GCP[] GCPs = m_tGdalDs.GetGCPs();
                    for (int i = 0; i < m_tGdalDs.GetGCPCount(); i++)
                    {
                        m_strGdalInfoTxt.AppendFormat("GCP[{0}]: Id={1}, Info={2}",
                                                      i, GCPs[i].Id, GCPs[i].Info).AppendLine();
                        m_strGdalInfoTxt.AppendFormat("          ({0},{1})->({2},{3},{4})",
                                                      GCPs[i].GCPPixel, GCPs[i].GCPLine, GCPs[i].GCPX, GCPs[i].GCPY, GCPs[i].GCPZ);
                        m_strGdalInfoTxt.AppendLine();
                    }
                    m_strGdalInfoTxt.AppendLine();

                    double[] transform = new double[6];
                    Gdal.GCPsToGeoTransform(GCPs, transform, 0);
                    m_strGdalInfoTxt.AppendFormat("GCP Equivalent geotransformation parameters: {0}",
                                                  m_tGdalDs.GetGCPProjection());
                    for (int i = 0; i < 6; i++)
                    {
                        m_strGdalInfoTxt.AppendFormat("[{0}]= {1}", i, transform[i].ToString());
                    }
                    m_strGdalInfoTxt.AppendLine();
                }

                //------------------------------------------------------------
                // Get raster band
                //------------------------------------------------------------
                for (int iBand = 1; iBand <= m_tGdalDs.RasterCount; iBand++)
                {
                    Band band = m_tGdalDs.GetRasterBand(iBand);
                    m_strGdalInfoTxt.AppendFormat("Band {0} :",
                                                  iBand).AppendLine();
                    m_strGdalInfoTxt.AppendFormat("   DataType: {0}",
                                                  Gdal.GetDataTypeName(band.DataType)).AppendLine();
                    m_strGdalInfoTxt.AppendFormat("   ColorInterpretation: {0}",
                                                  Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation())).AppendLine();
                    ColorTable ct = band.GetRasterColorTable();
                    if (ct != null)
                    {
                        m_strGdalInfoTxt.AppendFormat("   Band has a color table with {0} entries.",
                                                      ct.GetCount()).AppendLine();
                    }

                    m_strGdalInfoTxt.AppendFormat("   Description: {0}",
                                                  band.GetDescription()).AppendLine();
                    m_strGdalInfoTxt.AppendFormat("   Size ({0},{1})",
                                                  band.XSize, band.YSize).AppendLine();
                    int BlockXSize, BlockYSize;
                    band.GetBlockSize(out BlockXSize, out BlockYSize);
                    m_strGdalInfoTxt.AppendFormat("   BlockSize ({0},{1})",
                                                  BlockXSize, BlockYSize).AppendLine();
                    double val;
                    int    hasval;
                    band.GetMinimum(out val, out hasval);
                    if (hasval != 0)
                    {
                        m_strGdalInfoTxt.AppendFormat("   Minimum: {0}",
                                                      val.ToString()).AppendLine();
                    }
                    band.GetMaximum(out val, out hasval);
                    if (hasval != 0)
                    {
                        m_strGdalInfoTxt.AppendFormat("   Maximum: {0}",
                                                      val.ToString()).AppendLine();
                    }
                    band.GetNoDataValue(out val, out hasval);
                    if (hasval != 0)
                    {
                        m_strGdalInfoTxt.AppendFormat("   NoDataValue: {0}",
                                                      val.ToString()).AppendLine();
                    }
                    band.GetOffset(out val, out hasval);
                    if (hasval != 0)
                    {
                        m_strGdalInfoTxt.AppendFormat("   Offset: {0}",
                                                      val.ToString()).AppendLine();
                    }
                    band.GetScale(out val, out hasval);
                    if (hasval != 0)
                    {
                        m_strGdalInfoTxt.AppendFormat("   Scale: {0}",
                                                      val.ToString()).AppendLine();
                    }

                    for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                    {
                        Band over = band.GetOverview(iOver);
                        m_strGdalInfoTxt.AppendFormat("      OverView {0}:",
                                                      iOver).AppendLine();
                        m_strGdalInfoTxt.AppendFormat("         DataType: {0}",
                                                      over.DataType).AppendLine();
                        m_strGdalInfoTxt.AppendFormat("         Size ({0},{1})",
                                                      over.XSize, over.YSize).AppendLine();
                        m_strGdalInfoTxt.AppendFormat("         PaletteInterp: {0}",
                                                      over.GetRasterColorInterpretation().ToString()).AppendLine();
                    }
                }
            } catch (Exception ex) {
                m_ctrlLogger.FatalFormat("Application error: {0}", ex.Message);
            }
        }
Example #16
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            usage();
        }

        string file     = args[0];
        string file_out = args[1];

        try {
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            Driver     dv = null;
            Dataset    ds = null, ds_out = null;
            Band       ba = null, ba_out = null;
            ColorTable ct = null, ct_out = null;
            byte []    buffer;

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            ds = Gdal.Open(file, Access.GA_ReadOnly);
            ba = ds.GetRasterBand(1);
            ct = ba.GetRasterColorTable();

            if (ct != null)
            {
                Console.WriteLine("Band has a color table with " + ct.GetCount() + " entries.");
            }
            else
            {
                Console.WriteLine("Data source has no color table");
                return;
            }

            buffer = new byte [ds.RasterXSize * ds.RasterYSize];
            ba.ReadRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buffer,
                          ds.RasterXSize, ds.RasterYSize, 0, 0);

            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */
            dv = Gdal.GetDriverByName("GTiff");

            ds_out = dv.Create(file_out, ds.RasterXSize, ds.RasterYSize,
                               ds.RasterCount, ba.DataType, new string [] {});
            ba_out = ds_out.GetRasterBand(1);
            ct_out = new ColorTable(PaletteInterp.GPI_RGB);

            ba_out.WriteRaster(0, 0, ds.RasterXSize, ds.RasterYSize, buffer,
                               ds.RasterXSize, ds.RasterYSize, 0, 0);

            /* -------------------------------------------------------------------- */
            /*      Copying the colortable                                          */
            /* -------------------------------------------------------------------- */
            for (int i = 0; i < ct.GetCount(); i++)
            {
                ColorEntry ce = null, ce_out = null;

                ce     = ct.GetColorEntry(i);
                ce_out = new ColorEntry();

                ce_out.c1 = ce.c1;
                ce_out.c2 = ce.c2;
                ce_out.c3 = ce.c3;
                ce_out.c4 = ce.c4;

                ct_out.SetColorEntry(i, ce_out);

                ce.Dispose();
                ce_out.Dispose();
            }

            ba_out.SetRasterColorTable(ct_out);
        }
        catch (Exception e)
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }
Example #17
0
    private static void SaveBitmapPaletteDirect(Dataset ds, string filename, int iOverview)
    {
        // Get the GDAL Band objects from the Dataset
        Band band = ds.GetRasterBand(1);

        if (iOverview >= 0 && band.GetOverviewCount() > iOverview)
        {
            band = band.GetOverview(iOverview);
        }

        ColorTable ct = band.GetRasterColorTable();

        if (ct == null)
        {
            Console.WriteLine("   Band has no color table!");
            return;
        }

        if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
        {
            Console.WriteLine("   Only RGB palette interp is supported by this sample!");
            return;
        }

        // Get the width and height of the Dataset
        int width  = band.XSize;
        int height = band.YSize;

        // Create a Bitmap to store the GDAL image in
        Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);

        DateTime start = DateTime.Now;

        byte[] r = new byte[width * height];

        band.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
        // 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.Format8bppIndexed);

        try
        {
            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;

            int    stride = bitmapData.Stride;
            IntPtr buf    = bitmapData.Scan0;

            band.ReadRaster(0, 0, width, height, buf, width, height, DataType.GDT_Byte, 1, stride);
            TimeSpan renderTime = DateTime.Now - start;
            Console.WriteLine("SaveBitmapDirect fetch time: " + renderTime.TotalMilliseconds + " ms");
        }
        finally
        {
            bitmap.UnlockBits(bitmapData);
        }

        bitmap.Save(filename);
    }
Example #18
0
        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 static String DumpDatasetInfo(Dataset ds)
        {
            var sb = new StringBuilder();

            sb.AppendLine("Raster dataset parameters:");
            sb.AppendLine("  Projection: " + ds.GetProjectionRef());
            sb.AppendLine("  RasterCount: " + ds.RasterCount);
            sb.AppendLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */
            var drv = ds.GetDriver();

            if (drv == null)
            {
                sb.AppendLine("Can't get driver.");
                return(sb.ToString());
            }

            sb.AppendLine("Using driver " + drv.LongName);

            /* -------------------------------------------------------------------- */
            /*      Get metadata                                                    */
            /* -------------------------------------------------------------------- */
            string[] metadata = ds.GetMetadata("");
            if (metadata.Length > 0)
            {
                sb.AppendLine("  Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    sb.AppendLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                sb.AppendLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report "IMAGE_STRUCTURE" metadata.                              */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("IMAGE_STRUCTURE");
            if (metadata.Length > 0)
            {
                sb.AppendLine("  Image Structure Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    sb.AppendLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                sb.AppendLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report subdatasets.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("SUBDATASETS");
            if (metadata.Length > 0)
            {
                sb.AppendLine("  Subdatasets:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    sb.AppendLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                sb.AppendLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report geolocation.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("GEOLOCATION");
            if (metadata.Length > 0)
            {
                sb.AppendLine("  Geolocation:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    sb.AppendLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                sb.AppendLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report corners.                                                 */
            /* -------------------------------------------------------------------- */
            sb.AppendLine("Corner Coordinates:");
            sb.AppendLine("  Upper Left (" + GdalInfoGetPosition(ds, 0.0, 0.0) + ")");
            sb.AppendLine("  Lower Left (" + GdalInfoGetPosition(ds, 0.0, ds.RasterYSize) + ")");
            sb.AppendLine("  Upper Right (" + GdalInfoGetPosition(ds, ds.RasterXSize, 0.0) + ")");
            sb.AppendLine("  Lower Right (" + GdalInfoGetPosition(ds, ds.RasterXSize, ds.RasterYSize) + ")");
            sb.AppendLine("  Center (" + GdalInfoGetPosition(ds, ds.RasterXSize / 2.0, ds.RasterYSize / 2.0) + ")");
            sb.AppendLine("");

            /* -------------------------------------------------------------------- */
            /*      Report projection.                                              */
            /* -------------------------------------------------------------------- */
            string projection = ds.GetProjectionRef();

            if (projection != null)
            {
                SpatialReference srs = new SpatialReference(null);
                if (srs.ImportFromWkt(ref projection) == 0)
                {
                    srs.ExportToPrettyWkt(out var wkt, 0);
                    sb.AppendLine("Coordinate System is:");
                    sb.AppendLine(wkt);
                }
                else
                {
                    sb.AppendLine("Coordinate System is:");
                    sb.AppendLine(projection);
                }
            }

            /* -------------------------------------------------------------------- */
            /*      Report GCPs.                                                    */
            /* -------------------------------------------------------------------- */
            if (ds.GetGCPCount() > 0)
            {
                sb.AppendLine("GCP Projection: " + ds.GetGCPProjection());
                GCP[] gcps = ds.GetGCPs();
                for (int i = 0; i < ds.GetGCPCount(); i++)
                {
                    sb.AppendLine("GCP[" + i + "]: Id=" + gcps[i].Id + ", Info=" + gcps[i].Info);
                    sb.AppendLine("          (" + gcps[i].GCPPixel + "," + gcps[i].GCPLine + ") -> ("
                                  + gcps[i].GCPX + "," + gcps[i].GCPY + "," + gcps[i].GCPZ + ")");
                    sb.AppendLine("");
                }
                sb.AppendLine("");

                double[] transform = new double[6];
                Gdal.GCPsToGeoTransform(gcps, transform, 0);
                sb.AppendLine("GCP Equivalent geotransformation parameters: " + ds.GetGCPProjection());
                for (int i = 0; i < 6; i++)
                {
                    sb.AppendLine("t[" + i + "] = " + transform[i]);
                }
                sb.AppendLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Get raster band                                                 */
            /* -------------------------------------------------------------------- */
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++)
            {
                Band band = ds.GetRasterBand(iBand);
                sb.AppendLine("Band " + iBand + " :");
                sb.AppendLine("   DataType: " + Gdal.GetDataTypeName(band.DataType));
                sb.AppendLine("   ColorInterpretation: " + Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()));
                ColorTable ct = band.GetRasterColorTable();
                if (ct != null)
                {
                    sb.AppendLine("   Band has a color table with " + ct.GetCount() + " entries.");
                }

                sb.AppendLine("   Description: " + band.GetDescription());
                sb.AppendLine("   Size (" + band.XSize + "," + band.YSize + ")");
                band.GetBlockSize(out var blockXSize, out var blockYSize);
                sb.AppendLine("   BlockSize (" + blockXSize + "," + blockYSize + ")");
                band.GetMinimum(out var val, out var hasVal);
                if (hasVal != 0)
                {
                    sb.AppendLine("   Minimum: " + val);
                }
                band.GetMaximum(out val, out hasVal);
                if (hasVal != 0)
                {
                    sb.AppendLine("   Maximum: " + val);
                }
                band.GetNoDataValue(out val, out hasVal);
                if (hasVal != 0)
                {
                    sb.AppendLine("   NoDataValue: " + val);
                }
                band.GetOffset(out val, out hasVal);
                if (hasVal != 0)
                {
                    sb.AppendLine("   Offset: " + val);
                }
                band.GetScale(out val, out hasVal);
                if (hasVal != 0)
                {
                    sb.AppendLine("   Scale: " + val);
                }

                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                {
                    Band over = band.GetOverview(iOver);
                    sb.AppendLine("      OverView " + iOver + " :");
                    sb.AppendLine("         DataType: " + over.DataType);
                    sb.AppendLine("         Size (" + over.XSize + "," + over.YSize + ")");
                    sb.AppendLine("         PaletteInterpretation: " + over.GetRasterColorInterpretation());
                }
            }

            return(sb.ToString());
        }