Manipulating Pictures in Java- II
In my previous article, i discussed DigitalPicture Interface and SimplePicture class. Today we are going to write MyPicture class that inherits from SimplePicture class and allows us to add functionality of MyPicture class.
import java.awt.image.BufferedImage; import bookClasses.FileChooser; import bookClasses.SimplePicture; public class MyPicture extends SimplePicture { public MyPicture(String fileName) { super(fileName); } public MyPicture(int width, int height) { super(width,height); } public MyPicture(MyPicture copyPicture) { super(copyPicture); } public MyPicture(BufferedImage image) { super(image); } public String toString() { String output = "Picture, filename " + getFileName() + " height " + getHeight() + " width " + getWidth(); return output; } public static void main(String[] args) { String fileName = FileChooser.pickAFile(); MyPicture pic = new MyPicture(fileName); pic.explore(); } }
Now, we implemented constructors and toString method. To manipulate picture, create MyPicture object. In above program, FileChooser is used to pick a file. File name is stored as a string and later passed to new MyPicture(fileName); to create a MyPicture object of a selected picture. pic.explore() method of super class is used to show the selected picture in a JFrame. In next example, an additional method is added in MyPicture class. In coming articles, methods to manipulate picture such as adjust color to black, lightenPicture color and decrease red will be discussed. Here is an example to set all pixel colors to black. Simply i added adjustToBlack() method in MyPicture class.
import java.awt.Color; import java.awt.image.BufferedImage; import bookClasses.FileChooser; import bookClasses.Pixel; import bookClasses.SimplePicture; public class MyPicture extends SimplePicture { public MyPicture(String fileName) { super(fileName); } public MyPicture(int width, int height) { super(width, height); } public MyPicture(MyPicture copyPicture) { super(copyPicture); } public MyPicture(BufferedImage image) { super(image); } public void adjustToBlack() { Pixel[] pixelArray = this.getPixels(); Pixel pixel = null; int index = 0; while (index < pixelArray.length) { pixel = pixelArray[index]; pixel.setColor(Color.black); index++; } } public String toString() { String output = "Picture, filename " + getFileName() + " height " + getHeight() + " width " + getWidth(); return output; } public static void main(String[] args) { String fileName = FileChooser.pickAFile(); MyPicture pic = new MyPicture(fileName); pic.adjustToBlack(); pic.explore(); } }
No Responses