Understanding and decoding PNGs
While working on a game project in TS, we found ourselves needing a PNG decoder to create our objects metadata from pictures in a generic way.
We are coding using TS/JS in the browser, so the obvious solution is to use Canvas, but that wouldn’t be fun wouldn't it? So I decided to lookup the PNG format to create a decoder that will fit our needs.
Other than the official documentation, which can be heavy to read at first, i didn’t find much examples of how to implement that quickly, so I decided to share my experience and I hope it will help some of you getting started 😊
- Introduction
- I. Read the file and extract the data
- II. Understand PNG file’s format
- III. Parsing the metadata we need
- IV. Parsing the image content
In my project, I used a class Color to store the file’s pixel, but for our example, i’m going to output the results as an array of Uint8Array. Each array will store the information about one pixel (RGBA). Below is an example of the result we want implemented using canvas so you can see where we’re going. The index.html file is only there to have a visual representation of what we’re doing, it may seems useless for the first example (using canvas) but it will help us later.