Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8589183
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T22:59:23+00:00 2026-06-11T22:59:23+00:00

I try to rewrite pct2rgb.py script into C# (this script gets 8-bit TIFF image

  • 0

I try to rewrite pct2rgb.py script into C# (this script gets 8-bit TIFF image and changes the bit depth of it into 24-bit). It worked when its output was stored on the HDD. I want to change the script a little. It should return Dataset on-the-fly w/o storing it on the disk. It works… Almost… The problem is that the returned Dataset contains monochromatic data… I don’t really know why. Maybe it’s caused by the change of a driver from GTiff to MEM (Driver gTiffDriver = Gdal.GetDriverByName("MEM");). But I don’t know how to use GTiff driver and not to store the data on the HDD…

Here’s my class:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using OSGeo.GDAL;
using OSGeo.OGR;
using OSGeo.OSR;
using Driver = OSGeo.GDAL.Driver;
using Encoder = System.Drawing.Imaging.Encoder;
using PixelFormat = System.Drawing.Imaging.PixelFormat;

namespace RasterLoader
{
    public class TiffConverter
    {
        private string _format = "GTiff";
        private string _srcFileName = null;
        private int _outBands = 3;
        private int _bandNumber = 1;
        private string[] _args;

        public TiffConverter(string[] args)
        {
            _args = args;
        }

        public Dataset Convert8To24Bit()
        {
            Gdal.AllRegister();

            string[] argv = Gdal.GeneralCmdLineProcessor(_args, 0);

            int i = 1;
            while (i < argv.Count())
            {
                string arg = argv.ElementAt(i);
                switch (arg)
                {
                    case "-of":
                        i++;
                        _format = argv[i];
                        break;
                    case "-b":
                        i++;
                        _bandNumber = int.Parse(argv[i]);
                        break;
                    case "-rgba":
                        _outBands = 4;
                        break;
                    default:
                        if (string.IsNullOrEmpty(_srcFileName))
                        {
                            _srcFileName = argv[i];
                        }
                        else
                        {
                            Usage();
                        }
                        break;
                }
                i++;
            }

            string tmpFileName = _srcFileName + ".bak";

            // open source file
            Dataset srcDS = Gdal.Open(_srcFileName, Access.GA_ReadOnly);
            if (srcDS == null)
            {
                throw new Exception("Unable to open " + _srcFileName + ".");
            }

            Band srcBand = srcDS.GetRasterBand(_bandNumber);

            // ensure we recognise the driver
            Driver dstDriver = Gdal.GetDriverByName(_format);
            if (dstDriver == null)
            {
                throw new Exception("\"" + _format + "\" not registered.");
            }

            // build color table
            int[][] lookup = new int[4][];
            lookup[0] = Enumerable.Range(0, 256).ToArray();
            lookup[1] = Enumerable.Range(0, 256).ToArray();
            lookup[2] = Enumerable.Range(0, 256).ToArray();
            lookup[3] = new int[256];

            for (i = 0; i < 256; i++)
            {
                lookup[3][i] = 255;
            }

            ColorTable ct = srcBand.GetRasterColorTable();

            if (ct != null)
            {
                for (i = 0; i < Math.Min(256, ct.GetCount()); i++)
                {
                    ColorEntry entry = ct.GetColorEntry(i);
                    for (int j = 0; j < 4; j++)
                    {
                        switch (j)
                        {
                            case 0:
                                lookup[j][i] = entry.c1;
                                break;
                            case 1:
                                lookup[j][i] = entry.c2;
                                break;
                            case 2:
                                lookup[j][i] = entry.c3;
                                break;
                            case 3:
                                lookup[j][i] = entry.c4;
                                break;
                        }
                    }
                }
            }

            // create the working file
            string tifFileName = string.Empty;
            if (_format.Equals("GTiff", StringComparison.OrdinalIgnoreCase))
            {
                tifFileName = tmpFileName;
            }
            else
            {
                tifFileName = Path.Combine(Directory.GetParent(tmpFileName).Name, "temp.gif");
            }

//            Driver gTiffDriver = Gdal.GetDriverByName("GTiff");
            Driver gTiffDriver = Gdal.GetDriverByName("MEM");

            Dataset tifDS = gTiffDriver.Create(tifFileName, srcDS.RasterXSize, srcDS.RasterYSize, _outBands, DataType.GDT_Byte,
                                               new string[] {});

            // we should copy projection information and so forth at this point
            tifDS.SetProjection(srcDS.GetProjection());
            double[] geotransform = new double[6];
            srcDS.GetGeoTransform(geotransform);
            tifDS.SetGeoTransform(geotransform);

            if (srcDS.GetGCPCount() > 0)
            {
                tifDS.SetGCPs(srcDS.GetGCPs(), srcDS.GetGCPProjection());
            }

            // do the processing one scanline at a time
            for (int iY = 0; iY < srcDS.RasterYSize; iY++)
            {
                byte[] srcData = new byte[srcDS.RasterXSize*1];
                srcBand.ReadRaster(0, iY, srcDS.RasterXSize, 1, srcData, srcDS.RasterXSize, 1, 0, 0);

                for (int iBand = 0; iBand < _outBands; iBand++)
                {
                    int[] bandLookup = lookup[iBand];

                    int[] dstData = new int[srcData.Count()];
                    for (int index = 0; index < srcData.Count(); index++)
                    {
                        byte b = srcData[index];
                        dstData[index] = bandLookup[b];
                    }

                    tifDS.GetRasterBand(iBand + 1).WriteRaster(0, iY, srcDS.RasterXSize, 1, dstData,
                                                               srcDS.RasterXSize, 1, 0, 0);
                }
            }

            return tifDS;
        }

        private void Usage()
        {
            Console.WriteLine("Usage: pct2rgb.py [-of format] [-b <band>] [-rgba] source_file dest_file");
            throw new Exception("Bad arguments.");
        }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T22:59:24+00:00Added an answer on June 11, 2026 at 10:59 pm

    Ok. I found a solution. My problem was I tried to convert all the files (even in a good format). Then ct variable (ColorTable) was null.

    Solution:

    if (ct != null)
    {
    // same code here
    }
    else
    {
       return srcDS;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I try to rewrite and customize @Html.ActionLink , in one of overloads of this
try: recursive_function() except RuntimeError e: # is this a max. recursion depth exceeded exception?
I would rewrite a very simple url http://localhost/?page=me to http://localhost/me I have try this
Thanks Marko. I rewrite the code. try to make it simple. this time it
This is the rewrite rule that I am working with: RewriteRule (.*\.(jpe?g|gif|bmp|png))$ http://www.newurl.com/?image=$1 What
I try to rewrite this method using short-hand if: public string checkInputParamters(string baseUrl, string
After I've seen this PDC session I wanted to try to learn a bit
This row will certainly cause a little collision as it will try to rewrite
Try this code - import java.io.StringReader; public class StringReaderTest { public static void main(String[]
Try this piece of code - public class WhitespaceTest { public static void main(String[]

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.