Image-2 Code and Images

< CS101

In this section, we'll look at simple code to load and manipulate a digital image. Here we'll just manipulate one pixel at a time. In the next section, scaling up to operate on thousands of pixels at a time.

x.png

The image "x.png" is very simple - it's a very small black square with a white "x" at its center. Here is x.png:

PNG (Portable Network Graphics) is a format to store an image in a computer file, like JPG and GIF.

x.png Code Example

Our first image code example loads the x.png image into a variable and prints it. Run the code to see what it does. Try changing the image.setZoom(20) to use the number 10 or 30 instead.


image2-1

 

pixel.setRed(255) Example


image2-2

 

Pixel Set Red/Green/Blue Functions

noun.verb() Pattern

Aside: Image Functions Reference

For later reference, there is a separate image functions reference page which lists in one place all the image functions such as pixel.setRed(number) we are using here.

Experiments On Pixels (0, 0) and (1, 0)

To see how image.getPixel(x, y) and pixel.setRed(number) etc. work, we'll try the experiments listed below (use the "show" button to see the solution code).


image2-3

 

Example ProblemsSolution
Set pixel (0, 0) to be green.
pixel = image.getPixel(0, 0);
pixel.setGreen(255);
Set pixel (0, 0) to be yellow.
// Set red and green to 255, leave blue at 0
pixel = image.getPixel(0, 0);
pixel.setRed(255);
pixel.setGreen(255);
Set pixel (1, 0) to be yellow. Where is that pixel?
pixel = image.getPixel(1, 0);
pixel.setRed(255);
pixel.setGreen(255);
// getPixel(1, 0) retrieves the pixel
// one to the right of pixel (0, 0).
2 Pixels Set pixel (0, 0) to green (1, 0) to red.
// Set (0, 0) to green
pixel = image.getPixel(0, 0);
pixel.setGreen(255);

// Change pixel variable to refer to (1, 0)
// then set it to red
pixel = image.getPixel(1, 0);
pixel.setRed(255);
Set pixel (0, 0) to white.
pixel = image.getPixel(0, 0);
pixel.setRed(255);
pixel.setGreen(255);
pixel.setBlue(255);
Set pixel (0, 0) to be dark yellow -- set the necessary colors to 150 instead of 255.
pixel = image.getPixel(0, 0);
pixel.setRed(150);
pixel.setGreen(150);
Set pixel (1, 0) to be a light, pastel red.
pixel = image.getPixel(1, 0);
pixel.setRed(255);
pixel.setGreen(200);
pixel.setBlue(200);
// Set red at 255, green and blue equal but lower.

> exercises

Window size: 1366 x 738
Viewport size: 1366 x 623