How Interlacing Works in PNG

How Interlacing Works in PNG


3 min read

In PNG, there is a concept called the interlace method. It is about how pixels are arranged in a PNG datastream. With pixels arranged in a certain way, the progressive display can be achieved when the network is slow.

There are 2 interlace methods defined in PNG spec.

The first one is called the null method. In this method, pixels are arranged sequentially from left to right and from top to bottom. So for a 3*3 image, pixels may look like the below.

r g b a r g b a r g b a
r g b a r g b a r g b a
r g b a r g b a r g b a
r g b a r g b a r g b a

Note that the above pixels are still in a 1d array, I just make it 2d to look clear.

As you can see, with this method, as the data keeps coming, software can display images from left to right and from top to bottom progressively.

The second method is called Adam7. It uses a pattern to slide over the whole image and extract pixels according to the pattern. This is a bit complicated, let's break it down piece by piece.

Let's use a fake simple example pattern to show the whole process. Say the pattern is a 2*2 image, like below.

1 2
3 4

Each element stands for a pixel. And you can see here we got 4 elements and each in a different category(1,2,3,4).

Now, suppose we have an image below. Still, each element stands for a pixel.

a b c d e
f g h i j
k l m n o
p q r s t

What we will do now is slide the 2*2 pattern in the real image from left to right and top to bottom. So after sliding, each element will be assigned to each category according to its position in the pattern.

a(1) b(2) c(1) d(2) e(1)
f(3) g(4) h(3) i(4) j(3)
k(1) l(2) m(1) n(2) o(1)
p(3) q(4) r(3) s(4) t(3)

So let's say now we want to rearrange the pixel with order as categories 1, 2, 3, and 4. Then the datastream will be as below.

(1) a c e k m o
(2) b d l n
(3) f h j p r t
(4) g i q s

When the data stream keeps coming, instead of getting data from left to right and top to bottom, we will always get data like the overview of the whole image. So from the perspective of a user, it is a gradual process from vague to clear.

So now you get the idea, let's see what it is in reality. The real pattern is as below.

1 6 4 6 2 6 4 6
7 7 7 7 7 7 7 7
5 6 5 6 5 6 5 6
7 7 7 7 7 7 7 7
3 6 4 6 3 6 4 6
7 7 7 7 7 7 7 7
5 6 5 6 5 6 5 6
7 7 7 7 7 7 7 7

As you can see, there are 7 categories in total. For each category, 7 reduced images can be reconstructed. The below image is from the PNG spec, which how 16*16 image pixels got assigned in each category.

So that's all about interlacing in PNG. Hope you like it.