0

I haven't worked much with imaging before in C# and am confused by the values I am getting in my imageData byte array when passing it a 15x15 png. I would expect there to be 225 array elements (or more since each pixel would have a r,g,b,a value?), however it only has 124.

What are the 124 elements I'm getting? Additionally, I would like to be able to determine the color of each pixel. Is it possible to do this from the data given in the byte array or is there an entirely better way of doing this in C#?

Thank you

        Console.Write("Input file: ");
        string fileName = Console.ReadLine();
        Console.Write("Output file: ");
        string outputFileName = Console.ReadLine();

        FileInfo fileInfo = new FileInfo(Path.Combine(Environment.CurrentDirectory, fileName));

        byte[] imageData = new byte[fileInfo.Length];

        using (FileStream fs = fileInfo.OpenRead())
        {
            fs.Read(imageData, 0, imageData.Length);
        }
Studwell
  • 115
  • 10

1 Answers1

2

PNG files are actually rather complicated and I wouldn't recommend trying to read them without using a specialized library for the job. The reason you get fewer bytes than you expect is because the information is compressed, and must be decompressed in order to access the full information. Additionally, the PNG format is more complicated than just a list of color values per pixel.

I would recommend two things:

1) You can view the full PNG specification here: https://www.w3.org/TR/2003/REC-PNG-20031110/

It will explain in extreme detail all the steps needed to understand a PNG file, and perhaps convince you that it'd be better to use a library or built-in functionality to handle the files due to how much work it would be.

2) Consider working with bitmaps instead if you really want to get a low-level view of images. It's a much simpler format that would be easier to write your own parsers for. Otherwise, you should just use other people's code to manage loading the PNG files. You can find info on the BMP format here: https://learn.microsoft.com/en-us/windows/desktop/gdi/bitmap-storage

As for other methods of loading files, search stack overflow for loading images in C#, there are lots of other topics (e.g. Reading a PNG image file in .Net 2.0)

N.D.C.
  • 1,601
  • 10
  • 13