2

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

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

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

我的问题是,greyImage每次我增加对比度时 BufferedImage 对象是否都会更新myRaster

4

1 回答 1

3

查看 的源BufferedImagegetRaster()返回对缓冲图像中基础光栅对象的引用。所以如果你改变光栅,你就有效地改变了图像。

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

于 2012-09-03T13:19:22.293 回答