# 12.14. Coding Practice¶

A pixel is the smallest controllable element of a picture represented on the screen. Images are comprised of numerous individual pixels, and each pixel’s color sample has three numerical RGB (red, green, blue) components to represent the color of that pixel. The intensity value of each RGB component ranges from 0 to 255, where 0 is no intensity and 255 is highest intensity. Write the struct definition for Pixel, which has values for each component r, g, and b.

Below is one way to implement the program. We declare the Pixel struct and create the instance variables in order.

Selecting from: cp_12_AC_2q, cp_12_AC_2_pp

Let’s print out a Pixel! Write the Pixel member function printPixel, which prints out the values of the Pixel in this form: (r, g, b).

Below is one way to implement the program. We use the scope resolution operator to make printPixel a Pixel member function.

Selecting from: cp_12_AC_4q, cp_12_AC_4_pp

Somebody photobombed our image! What if we wanted to crop the photobomber out? Let’s write the Image member function cropImage, which takes four paramenters, a start and stop row and a start and stop column. It then modifies the matrix to the cropped matrix.

Below is one way to implement the program. First we make a new matrix with the correct amount of rows. Then we push back the pixels we want into the new matrix. Afterwards, we must update the height and width of the Image and set the Image's matrix equal to the new one we created.

Selecting from: cp_12_AC_6q, cp_12_AC_6_pp

When you take a selfie on your phone, the image is mirrored. We can do the same to an image by flipping it horizontally. Write the Image member function flipHorizontal, which flips an image horizontally. Use the swapPixel function we created previously.

Below is one way to implement the program. We loop through each row in the matrix. We create start and end indices and repeatedly swap pixels, moving both indices toward the middle. Once they meet in the middle, we have finished flipping the image.

Let’s write the Image member function called createBorder, which sets the Pixels on the edge of an Image to a given Pixel.
Below is one way to implement the program. We set the first and last row and first and last column of Pixels in the Image to the given Pixel.