Creating an Image Algorithmically

Solve It

In this example, we are going to create an image that looks like two planets in space, using mathematical functions.

The main idea is to map the value of one aspect of the picture into another aspect of the picture. In this case, we are going to map the distance between points into red, green, or blue values. We need to begin by writing a function that gives us the distance between two points (we'll just look up the equation and turn it into code). Now, for the main algorithm, we start by creating a blank image and writing the loop that will let us fill in the color values for each pixel.

The "planet" effect is achieved by deciding on a point for the planets to be, then coloring the areas around the planets by mapping the distance from the planet to a color brightness. The closer the pixel is to the planet, the closer the color of the pixel is to the planet's color. In this example, we have chosen the point (100,100) to be a red planet and (200,200) to be a green planet.

We can use the same idea to make a gradient effect in the background. We know that the main diagonal of an image is the points where the x value equals the y value. We can get an interesting visual effect by using the difference between the x and y values to map to the blue value of the pixels. The image appears darker near the main diagonal.

Finally, we add "stars" by randomly coloring some pixels white.

As you look at this code example, you may ask yourself, "Why did they use 1.5 there? Why not 1.2 or 1.7?" The answer to this type of question is often not very mathematical. Instead, it was because we played with the code until we got the visual effect we liked. We encourage you to tweak both this code example and your own code to see what difference it makes in the image. See if you can figure out why the image looks the way it does based on your change and which version you like the best.

Code It

function dist(pixel, x,y) { var dx = pixel.getX() - x; var dy = pixel.getY() - y; return Math.sqrt(dx * dx + dy *dy); } //start with a blank image var output = new SimpleImage(320,320); //Make something here! for (var pixel of output.values()){ if (dist(pixel, 100,100)< 50){ pixel.setRed(255-4*dist(pixel,100,100)); } else if (dist(pixel, 200,200)< 80){ pixel.setGreen(255-3*dist(pixel,200,200)); } else if (Math.random() > 0.995) { pixel.setRed(255); pixel.setGreen(255); } pixel.setBlue(Math.max(1.5*pixel.getY() - pixel.getX(), pixel.getX() - 1.5* pixel.getY())); } //print whatever you made print(output);

See It

 
 

Available Images

Drop your images onto the area above to make it available within your code editor on this page. Note: your images will not be uploaded anywhere, they will stay on your computer.