2017-04-07 26 views
0

我有一张图片,我试图去除所有绿色像素。我如何使用简单的java和2D数组来做到这一点?使用java替换图片中的绿色像素

到目前为止,我的代码如下所示:(。现在,我想只能用白色像素替换绿色像素,因为我不知道如何完全删除像素)

public void removeGreen() { 

     Picture pic = new Picture("IMG_7320.JPG"); 
     Pixel pixel = null; 
     for (int row = 0; row < pic.getHeight(); row++) { 
      for (int col = 0; col < pic.getWidth(); col++) { 
       pixel = getPixel(row,col); 
       pixel.getColor(); 
       if(pixel.getRed() < 40 & pixel.getBlue() < 160 & pixel.getGreen() > 220) { 
        Color white = new Color(255,255,255); 
        pixel.setColor(white); 
       } 
      } 
     } 
    } 

而且我使用测试removeGreen()方法,在我的主要方法的代码,如下所示:

//method to test removeGreen 

    public static void testRemoveGreen() { 

     Picture me = new Picture("IMG_7320.JPG"); 
     me.explore(); 
     me.removeGreen(); 
     me.explore(); 
    } 


所以,我的代码现在看起来像这样:

公共无效removeGreen(图像PIC){

为(INT行= 0;行< pic.getHeight();行++){

for (int col = 0; col < pic.getWidth(); col++) { 
     Pixel pixel = pic.getPixel(row,col); 

     if((pixel.getRed() < 40) && (pixel.getBlue() < 160) && (pixel.getGreen() > 220)) { 
      Color white = new Color(255,255,255); 
      pixel.setColor(white); 
     } 
    } 

} }

和我的主要方法仍是相同的。我仍然不明白为什么该方法无法正常工作。

+1

所以你想用另一个图像的像素替换它们?一种绿色屏幕?澄清你的问题。如果不按照顺序调整图像大小,则永远不能删除像素,因此,假设您使用的图像格式支持Alpha通道,则最好做到透明。 – Havenard

+1

另外,在我看来,你在收集数据和修改图像'this''的同时迭代图像'pic',做出决定。 – Havenard

回答

0

以下表明通过的pic参数已更改。

public static void removeGreen(Picture pic) { 
     for (int row = 0; row < pic.getHeight(); row++) { 
      for (int col = 0; col < pic.getWidth(); col++) { 
       Pixel pixel = pic.getPixel(row,col); 
       if (pixel.getRed() < 40 && pixel.getBlue() < 160 
         && pixel.getGreen() > 220) { 
        pixel.setColor(Color.white); 
       } 
      } 
     } 
    } 

&&是一条捷径AND:x && y()不会叫y是x是假的。

注意pic.getPixel。如果removeGreen用作Picture的方法,则删除参数和static关键字,并删除pic.

public static void testRemoveGreen() { 
    Picture me = new Picture("IMG_7320.JPG"); 
    me.explore(); 
    removeGreen(me); 
    me.explore(); 
} 

由于.jpg,JPEG格式不具有透明度,因此需要将某些颜色(如白色)显示为“背景”。

相关问题