我正在编写一个程序,该程序结合了3张图像的RGB像素值,例如图像1的红色像素,图像2的绿色像素和图像3的蓝色像素,然后我要为其创建最终图像。
我使用下面的代码,但这似乎在x1和x2相同的情况下递增x2和x3,即没有为每个图像的相同坐标给出正确的像素值。

for (int x = 0; x < image.getWidth(); x++) {
            for (int x2 = 0; x2 < image2.getWidth(); x2++) {
                for (int x3 = 0; x3 < image3.getWidth(); x3++) {

       for (int y = 0; y < image.getHeight(); y++) {
           for (int y2 = 0; y2 < image2.getHeight(); y2++) {
               for (int y3 = 0; y3 < image3.getHeight(); y3++) {


因此,我想知道是否有人可以告诉我如何遍历同一坐标的3张图像,例如读取1张图像中的1张,并相应地记录红色,绿色和蓝色值。道歉,如果没有完全意义,则有点难以解释。我可以很好地迭代一幅图像的值,但是当我添加另一幅图像时,事情就开始出错了,因为显然它要复杂得多!我在想创建一个数组并替换相应的值可能会更容易,因为既不确定如何有效地执行操作也是如此。

谢谢

最佳答案

如果我正确理解了您的问题,也许您可​​以尝试以下方法:

public BufferedImage combine(final BufferedImage image1, final BufferedImage image2, final BufferedImage image3){
    final BufferedImage image = new BufferedImage(image1.getWidth(), image1.getHeight(), image1.getType());
    for(int x = 0; x < image.getWidth(); x++)
        for(int y = 0; y < image.getHeight(); y++)
            image.setRGB(x, y, new Color(new Color(image1.getRGB(x, y)).getRed(), new Color(image2.getRGB(x, y)).getGreen(), new Color(image3.getRGB(x, y)).getBlue()).getRGB());
    return image;
}


对于更具可读性的解决方案:

public BufferedImage combine(final BufferedImage image1, final BufferedImage image2, final BufferedImage image3){
    final BufferedImage image = new BufferedImage(image1.getWidth(), image1.getHeight(), image1.getType());
    for(int x = 0; x < image.getWidth(); x++){
        for(int y = 0; y < image.getHeight(); y++){
            final int red = new Color(image1.getRGB(x, y)).getRed();
            final int green = new Color(image2.getRGB(x, y)).getGreen();
            final int blue = new Color(image3.getRGB(x, y)).getBlue();
            final int rgb = new Color(red, green, blue).getRGB();
            image.setRGB(x, y, rgb);
        }
    }
    return image;
}


我的解决方案基于所有3张图像都是相似的(尺寸和类型相同)的假设。

关于java - 具有多个增量器的Java for循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19608593/

10-11 22:28
查看更多