14  Excel/VBA Photoshop

Images are represented in computers as a matrix of pixels. Each pixel has a color represented by three values: Red, Green, and Blue (RGB). The combination of these three colors generates the color of the pixel. For example, the color white is represented by the RGB values (255, 255, 255), and the color black is represented by the RGB values (0, 0, 0).

In this exercise, you will write VBA code to manipulate images in Excel. The images will be represented in the .PPM format, which is a simple format to represent images. The .PPM format is a text file that contains the image’s dimensions (number of rows and columns) and the RGB values of each pixel.

14.1 PPM Format

The .PPM format, also known as Portable Pixel Map, is a text file that contains the image’s dimensions (number of rows and columns) and the RGB values of each pixel. The first line of the file contains the image type, which can be P3 (ASCII) or P6 (binary). The second line contains the number of columns and rows of the image. The third line contains the maximum value of the RGB values (usually 255). The following lines contain the RGB values of each pixel. The RGB values are separated by spaces.

14.2 Instructions

  1. Write a sub DrawImage(SourceImageSheetName As String) that 1) reads the content of a .PPM image in the worksheet SourceImageSheetName, and 2) draws the corresponding image in a new worksheet labeled SourceImageSheetName & "_Output". Example:

    Input image (.ppm):

    P3
    2 2
    255
    255 0   0   0   0   0
    0   0   0   255 0   0

    Input content pasted in worksheet “BlackRedSquarePPM”:

    Output (worksheet "BlackRedSquare_Output")

    Tip: Check your sub using PPM image data with different dimensions (number of rows and columns) designed by you.

  2. Write a sub FlipHorizontal(SourceImageSheetName As String) that 1) reads the content of a .PPM image in the worksheet SourceImageSheetName and 2) draws the image flipped horizontally in a new “SourceImageSheetName & "_OutputFlipHorizontal".

  3. Write a sub DrawImageGrayScale(SourceImageSheetName As String) that 1) reads the content of a .PPM image in the worksheet SourceImageSheetName, and 2) draws the corresponding image in shades of gray in a new worksheet labeled SourceImageSheetName & "_OutputGrayScale". To convert an RGB color to grayscale, use the formula GrayScale = (Red + Green + Blue)/3. Example:

    Red Green Blue Grayscale RGB
    255 0 0 85 (85, 85, 85)
    25 230 122 125 (125, 125, 125)
    0 255 0 85 (85, 85, 85)

    Notice that the grayscale value is an Integer.

    TIP: Use the native function:

    VBA.RGB(Red As Integer, Green As Integer, Blue as Integer)`

    to change a color cell. Example:

    'Change cell (1,1) background color to red
    Cells(1,1).Interior.Color = VBA.RGB(255, 0, 0)