Watch this video free by signing up

Storing Colors in a Pixel Grid

To create our page, we’re going to be storing pixels in an Ethereum smart contract.

To store colors, we have to pick a format to encode them in. Every byte we store on the Ethereum blockchain costs ether. So it’s important that we’re careful about what format we use to store our pixels.

Thankfully, we don’t need to invent our own format, we’re going to use 24-bit RGB color.

What that means is that we’re going to store 1 byte each for the red, green, and blue component for each pixel.

For example, when we use the color picker in Chrome, we can specify colors in RGBA.

RGBA stands for red-green-blue-alpha. Each one of these is called a “channel”, as in, the red channel or the alpha channel. The alpha specifies the transparency of the color, which we’re not going to use, but you could if you wanted to.

Notice that as we pick a different color, the values for red, green, and blue vary as a number between 0 and 255.

That’s because each channel is represented by 1 byte. And, I can understand if you haven’t been working with bits and bytes recently, so recall that 1 byte is 8 bits.

A bit can hold two values, either one or zero. And with 8 bits we can hold 2 to the 8th values, which is 256 values.

2 ** 8
// => 256

In JavaScript we can convert numbers between bases like this:

parseInt(255, 10).toString(2)
// => '11111111'
parseInt(235, 10).toString(2)
// => '11101011'

This converts 255 in base-10 into binary base-2.

There’s another common way to view the bytes of a color code and that is hex encoding. If you’ve done any web development at all you’ve certainly seen this:

 

Subscribe to get the full text of this lesson

and the entire library of videos, sample code, and tutorials.