import java.awt.image.*; import java.io.*; import javax.imageio.ImageIO; import java.awt.Color; import idraw.*; import colors.*; import geometry.*; /** * This class allows the user to set individual pixels * for an image of the given height and width to the desired * RGB color and to save the resulting image as a .png file * * @author Viera K. Proulx * @since 8 April 2010 */ public class ImageBuilder2{ int width; int height; /** the buffer that saves the user-generated image */ BufferedImage image; Canvas canvas; ImageBuilder2(int width, int height){ this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); this.canvas = new Canvas(width, height); //this.canvas.show(); } /** * Set the specified pixel in the image * to the given RGB color. * * @param x the x coordinate of the pixel * @param y the y coordinate of the pixel * @param r the red shade value of the pixel * @param g the green shade value of the pixel * @param b the blue shade value of the pixel */ public void setColorPixel(int x, int y, int r, int g, int b){ Color c = new Color(this.resetShade(r), this.resetShade(g), this.resetShade(b)); this.image.setRGB(x, y, c.getRGB()); this.canvas.drawDisk(new Posn(x, y), 1, c); } /** * Get the color of the pixel at the given coordinates * @param x the x coordinate of the specified pixel * @param y the y coordinate of the specified pixel * @return the color of the specified pixel in this image */ public Color getColorPixel(int x, int y){ return new Color(this.image.getRGB(x, y)); } /** *

Make sure the color shade is in the [0, 255] bounds.

*

Replace negative shade value with 0

*

Replace shade value over 255 with 255

* * @param shade the given shade * @return shade adjusted to fit the bounds */ public int resetShade(int shade){ if (shade < 0) shade = 0; else if (shade > 255) shade = 255; return shade; } /** * Save the data stored in the image * to a file with the given name * @param filename the given file name */ public void saveImage(String filename){ try{ File marspic = new File(filename + ".png"); ImageIO.write(this.image, "png", marspic); this.canvas.show(); } catch(IOException e){ System.out.println("Error when writing image file"); } } }