Metalfusion
Metalfusion

Reputation: 53

Why does 1bpp PNG image file size increase when the colors are inverted?

When I generate black-and-white png images with 1 bit per pixel indexed color, it seems to make a noticeable difference in the file size if if I choose to use black background over white one. The attached images should have exactly the same information, and both are created by .NET 4's Bitmap.Save() function.

Why is the image with white background significantly larger when compressed?

Black background: 4.62KB Black background 4.62KB

White background: 5.67KB White background: 5.67KB

Upvotes: 5

Views: 1236

Answers (1)

user479870
user479870

Reputation:

The answer is perhaps surprising, but quite simple, and lies in the PNG format itself.

As already mentioned, PNG applies a filter to each line. This helps compression for images which have a pattern within a line or between neighbouring lines. In this case, the image is pretty much single color with just a few dots sprinkled in, so using no filter yields the best result.

The filter byte is stored as the first byte of each image line. This is key.

The filter step itself results in a sequence of bytes of the same size as the incoming sequence, but in a different representation, preceded by a filter type byte. [...] The filter type byte is not considered part of the image data, but it is included in the datastream sent to the compression step.

With no filter used, the filter byte is 0x00. Example of a black 1-bit 4x4 image, with filter bytes bolded.

00 0 0 0
00 0 0 0
00 0 0 0
00 0 0 0

The same image as a flat sequence, as received by the compressor.

00 0 0 000 0 0 000 0 0 000 0 0 0

And the image with pixels inverted.

01 1 1 101 1 1 101 1 1 101 1 1 1

It's obvious which compresses better.

In the white background image provided, streams of 0x01 are regularly interrupted by a 0x00 filter byte, with a negative effect on compressibility. In the black background image, there is no such effect.

Upvotes: 9

Related Questions