2013-10-26 42 views
0

我写一个程序,它结合了3个图像,例如RGB图像的RGB像素值。图像1的红色像素,图像2的绿色像素和图像3的蓝色像素,然后我想要创建它的最终图像。 即时通讯使用下面的代码,但这似乎是递增x2和x3,而x1是相同的,即没有给每个图像的相同坐标正确的像素值。Java for for循环与多个增量器

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每个图像并记录红,绿,蓝相应的价值。道歉,如果它没有完全意义,这有点难以解释。我可以很好地迭代一个图像的值,但是当我添加另一个图像时,事情开始有点错误,因为显然它有点复杂!我认为创建一个数组并更换相应的值可能会更容易一些,但是不知道如何有效地做到这一点。

感谢

+1

图像尺寸是否相同?如果他们不在,你会怎么做? – Tyler

+0

它们的大小是一样的,它将同一图像的多个波段组合在一起。我知道如果他们不是相同的大小,它可能会有问题,但对于这个程序,我不需要考虑这一点:) – user2517280

+0

我相信Josh M已经提供了你的答案。 – Tyler

回答

2

如果我正确理解你的问题,也许你可以尝试这样的:

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张图片都是相似的(相同的尺寸和类型)。

+0

非常感谢,当我尝试时,保存的图像与第一个输入的图像是一样的,任何想法为什么? – user2517280

+0

您确定您正确调用该方法吗? 'BufferedImage combinedImage = combine(img1,img2,img3);'? –

+0

我忘了添加'静态',然后给了我一个错误,但它的工作现在:)图像出来相当蓝色,但即时猜测这是预期?无论哪种方式工作:)谢谢! – user2517280

1

你可以试试double,只是为了遍历坐标。我知道它不起作用,但这个想法可能会有所帮助。

for(int i = 0; i < width; i++) { 
    for(int j = 0; j < height; j++) { 
     int R = image1.R(x, y); 
     int G = image2.G(x, y);    
     int B = image3.B(x, y); 
     // Some other stuff here 
    } 
}