import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.Color;
/**
* 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 ImageBuilder{
int width;
int height;
/** the buffer that saves the user-generated image */
BufferedImage image;
ImageBuilder(int height, int width){
this.image = new BufferedImage(height, width,
BufferedImage.TYPE_INT_ARGB);
}
/**
* Set the specified pixel in the image
* to the given RGB color.
*
* @param x the x coordinate of the pixel
* @param ythe 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());
}
/**
*
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 theimage
* 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);
}
catch(IOException e){
System.out.println("Error when writing image file");
}
}
}