import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; /** Let's make a French flag: blue, white, red. * Creating an image in Java is pretty simple. But don't memorize the * syntax. There are 3 steps: create an image object, write pixel * values, and finally put the image object into a file. * The interesting part is writing the pixel values. We use the RGB * (Red, Green, Blue) color system. We need to tell each pixel how much * of each primary color we want, in the range from 0-255. * When we call the setRBG() function, we need to pass it this number: * 65536*R + 256*G + B. */ public class Flag { public static void main(String [] args) { // First, create an image object. // The parameters to the constructor are: // width, height, and image type (we use 1) BufferedImage image = new BufferedImage (300,200,1); // Second, write pixel values into the image. // The French flag has 3 equal portions of blue, white, red. // In all 3 cases, we want the height(y) to range 0-199. // The blue portion is where x is 0-99, etc. // Note: in Cartesian coordinates, x is horizontal, y is vertical. int blueNumber = 0*65536 + 0*256 + 255; int whiteNumber = 255*65536 + 255*256 + 255; int redNumber = 255*65536 + 0*256 + 0; for (int x = 0; x < 300; ++x) for (int y = 0; y < 200; ++y) { if (x < 100) image.setRGB(x, y, blueNumber); else if (x < 200) image.setRGB(x, y, whiteNumber); else image.setRGB(x, y, redNumber); } // Third, write the image to a file. // May automatically throw "IOException" try { ImageIO.write(image, "png", new File ("france.png")); } catch (IOException e) { System.out.printf("Encountered problem trying to write to file\n"); } } }