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.
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.
image = new SimpleImage("x.png");
image.setZoom(20);-- set zoom option to 20 (10, 20, ... whatever)
print(image);-- print out image as usual
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.
pixel = image.getPixel(0, 0);
pixel.setRed(255);-- set red value of that pixel
pixel.setRed(number);-- set the red value of the pixel to be the given number (0..255)
pixel.setGreen(number);-- set the green value
pixel.setBlue(number);-- set the blue value
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.
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).
|Set pixel (0, 0) to be green.|
|Set pixel (0, 0) to be yellow.|
|Set pixel (1, 0) to be yellow. Where is that pixel?|
|2 Pixels Set pixel (0, 0) to green (1, 0) to red.|
|Set pixel (0, 0) to white.|
|Set pixel (0, 0) to be dark yellow -- set the necessary colors to 150 instead of 255.|
|Set pixel (1, 0) to be a light, pastel red.|