gpt4 book ai didi

java - 更改 WritableRaster 对象会影响 bufferedImage 对象

转载 作者:行者123 更新时间:2023-12-04 05:33:48 26 4
gpt4 key购买 nike

我正在编写一个程序来使用以下代码对图像执行各种操作:

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();
}
}
}

}

所有操作都在可写光栅对象上完成 myRasterImageOperation方法, myRaster使用 BufferedImage 对象创建 greyImage .

现在,在第一次运行时,当我(比方说)将图像的对比度增加某个因子时,它会给出正确的结果,第二次如果我应用完全相同的对比度,它会在先前增强的图像上执行该操作,不是原始的,因此,在第二次运行中它给了我更高的对比度。

我的问题是,BufferedImage 对象是 greyImage每次我在 myRaster 上增加对比度时都会得到更新?

最佳答案

查看 BufferedImage 的来源, getRaster()返回对缓冲图像中底层光栅对象的引用。因此,如果您更改光栅,您实际上已经更改了图像。

您可能想要制作原始图像的副本,然后对副本进行操作。这应该保留原件。

关于java - 更改 WritableRaster 对象会影响 bufferedImage 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12248613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com