将两张图像合二为一

时间:2014-11-08 12:21:41

标签: java image rgb

我是Java的新手,我对此代码有疑问。 第一部分完美运行,它获取输入图像的每个像素的RGB值,然后将值乘以特定数字并将结果保存为新图像。

try {
    File input = new File("obr4.png");
    image2 = ImageIO.read(input);
    int width = image2.getWidth();
    int height = image2.getHeight();
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = new Color(image2.getRGB(j, i));

            int red = (int) (c.getRed() * Math.abs(text2value));
            if (red > 255) {
                red = 255;
            }
            int green = (int) (c.getGreen() * Math.abs(text2value));
            if (green > 255) {
                green = 255;
            }
            int blue = (int) (c.getBlue() * Math.abs(text2value));
            if (blue > 255) {
                blue = 255;
            }

            Color newColor = new Color(red, green, blue);
            image2.setRGB(j, i, newColor.getRGB());
            //System.out.println("Row: "+i+" Column: "+j+" Red: "+red+" Green: "+green+" Blue: "+blue);
        }
    }
    File output2 = new File("grayscale2.jpg");
    ImageIO.write(image2, "jpg", output2);
    repaint();

} catch (Exception e2) {
    System.out.println("Error");
}

具有不同值的相同代码也适用于第二张图像。

现在棘手的部分:我希望将两个新创建的图像放在一张图片中 - 只需从pic1pic2获取所有像素值,将它们添加到一起并打印结果。 到目前为止,我有这段代码:

try {
    File input1 = new File("grayscale1.jpg");
    File input2 = new File("grayscale2.jpg");

    finalImage1 = ImageIO.read(input1);
    finalImage2 = ImageIO.read(input2);

    for (int i = 0; i < 256; i++) {
        for (int j = 0; j < 256; j++) {
            Color c = new Color(finalImage1.getRGB(j, i));
            int red1 = (int) (c.getRed());
            int green1 = (int) (c.getGreen());
            int blue1 = (int) (c.getBlue());

            Color o = new Color(finalImage2.getRGB(j, i));
            int red2 = (int) (o.getRed());
            int green2 = (int) (o.getGreen());
            int blue2 = (int) (o.getBlue());

            int red = (red1 + red2) / 2;
            if (red > 255) {
                red = 255;
            }
            int green = (green1 + green2) / 2;
            if (green > 255) {
                green = 255;
            }
            int blue = (blue1 + blue2) / 2;
            if (blue > 255) {
                blue = 255;
            }

            Color newColor = new Color(red, green, blue);
            finalImage.setRGB(j, i, newColor.getRGB());
            //  System.out.println("Row: "+i+" Column: "+j+" Red: "+red+" Green: "+green+" Blue: "+blue);
        }
    }
    File output = new File("finalImage.jpg");
    ImageIO.write(finalImage, "jpg", output);
} catch (Exception e) {
    System.out.println("Sum error");
}

它应该与之前的代码相同,但它没有。总是给出&#34;总和错误&#34;。这个问题似乎在创建finalImage的某个地方,因为如果我将值打印到控制台中,它似乎没问题。 如果您有任何想法,有什么问题,请告诉我。谢谢

0 个答案:

没有答案