I am writing a program to perform various operations on an image using the following code:
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class BrightnessContrast {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
int i, j, choice = 1;
String imgName;
boolean flag = true;
String imagePath = "images/test.jpg";
BufferedImage myImage = ImageIO.read(new File(imagePath));
int height = myImage.getHeight();
int width = myImage.getWidth();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final BufferedImage greyImage = new BufferedImage(width, height,BufferedImage.TYPE_BYTE_GRAY);
Graphics grp = greyImage.getGraphics();
grp.drawImage(myImage, 0, 0, null);
File f2 = new File("images/BrightnessContrastTestInput.jpg");
try {
ImageIO.write(greyImage, "JPG", f2);
} catch (IOException x) {
x.printStackTrace();
}
while (flag == true) {
System.out
.println(" 1.Brightness \n 2.Contrast \n 3.EXIT!");
choice = Integer.parseInt(br.readLine());
switch (choice) {
case 1:
//increase brightness
case 2:
//increase contrast
case 3:
flag = false;
break;
default:
System.out.println("Invalid Option. Please try again.");
break;
}
}
}
public static void ImageOperation(BufferedImage greyImage) {
WritableRaster myRaster = greyImage.getRaster();
for (j = 0; j < greyImage.getHeight(); j++) {
for (i = 0; i < greyImage.getWidth(); i++) {
//some logic to increase contrast and brightness
}
}
File f = new File("images/"+imgName);
try {
ImageIO.write(greyImage, "JPG", f);
} catch (IOException x) {
x.printStackTrace();
}
}
}
}
All the manipulations are done on the writable raster object myRaster in ImageOperation method, myRaster is created using a BufferedImage object greyImage.
Now, in the first run when i (let’s say) increase contrast of an image by a certain factor, it gives a proper result, in the second time if i apply the exact same amount of contrast it does that operation on the previously enhanced image, not the original one, thus, in the second go it gives me a higher contrast.
my question is that, is the BufferedImage object greyImage getting updated each time i increase contrast on the myRaster?
Looking at the source for
BufferedImage,getRaster()returns a reference to the underlying raster object within the buffered image. So if you change the raster, you have effectively changed the image.You might want to make a copy of the original image and then operate on the copy. This should preserve the original.