.netimagebitmappngc#-2.0

How can I manually read a PNG image file and manipulate pixels in C#?


There are already lots of classes and functions supplied with the .NET to manipulate Images including PNG. Like Image, Bitmap, etc. classes. Suppose, I don't want to use those classes.

If I want to manually read/write a PNG image as a binary file to work with pixels then how can I do that?

using(FileStream fr = new FileStream(fileName, FileMode.Open)) 
{
      using (BinaryReader br = new BinaryReader(fr))
      {
          imagesBytes= br.ReadBytes((int)fr.Length);
      }  
}

How can I get hold of individual pixels to manipulate them?


Solution

  • Although it might be a bit late to bring up this conversation, I wanted to share that I got inspired by this post and wrote my own program in C# to access the pixels of a PNG image. You can check out my repository CrossPlatformSupportOnlyPNG

    However, unlike BMP format, pixels in PNG files are compressed with a different algorithm to reduce their size. It took me a few months to go through Wikipedia documentation on this topic, and I must admit that I got overwhelmed with information and gave up for a while.

    With .NET Core, I suggest you that to check out some online repositories or libraries to figure out how to access pixels in PNG files. because so many library's were made to store image in server. So decently their will be one which read the pixel array.

    so for starter you need to read the open the image as stream.

    using (var reader = File.OpenRead(inputFile))
    {
      //code goes here.
    }
    

    or you can just load the whole image in the memory with

    File.ReadAllBytes(inputFile)
    

    then you need to slice them into bytes and convert those slices into human readable data. but what i suggest you first you go through this Link. Understand what is inside the png file. then write your code. As far i have learned through out my journey what you are looking for is IDAT header. but the real problem arrives when you have to decode it into actual pixels. that is because of different algorithms use for compression. so good luck if you continues the png reading and the repo should give you a head start.
    or you can check SixLabors.ImageSharp library.