我正在编写一个程序,使用以下代码对图像执行各种操作:
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();
}
}
}
}
所有操作都在myRaster
方法中的可写光栅对象ImageOperation
上完成,myRaster
是使用BufferedImage对象greyImage
创建的。
现在,在第一次运行时,当我(假设)通过某个因子增加图像的对比度时,它会给出正确的结果,如果我应用完全相同的对比度,它会在第二次运行时对以前增强的图像,而不是原始的图像,因此,在第二次去它给我一个更高的对比度。
我的问题是,每当我增加greyImage
的对比度时,BufferedImage对象myRaster
是否会更新?
答案 0 :(得分:3)
查看BufferedImage
的来源,getRaster()
返回对缓冲图像中基础栅格对象的引用。因此,如果更改光栅,则可以有效地更改图像。
您可能想制作原始图像的副本,然后对副本进行操作。这应该保留原文。