2016-07-29 50 views
-2

我对这段代码感到迷茫,我正在努力。我不得不使用java来制作一张灰度图。我有基本代码,但我不知道要放入什么内容,不会使整个屏幕变灰。我正在努力研究它,但我迷了路,不知道下一步该做什么。它目前的方式是,只需要一张图像通过一个过程,然后使其新版本完全相同,但我需要使新版本变成灰色版本。 访问:https://ask.extension.org/uploads/question/images/attachments/000/037/087/image_300x300%2523.jpg?1406470060对于我正在使用的树图片。使用Java的图片上的灰度

import java.awt.*;          //import the awt graphics package 
class TrueColors            //start of the class 
{ 
TrueColors()        //start of the main method 
{  
    Picture pictureObj = new Picture("trunk.jpg");  
    pictureObj.explore();           
    int redValue = 0; int greenValue = 0; int blueValue = 0;   

    Pixel targetPixel = new Pixel(pictureObj, 0,0);    
    Color pixelColor = null;             

    for(int y=0; y < pictureObj.getHeight(); y++)     
    { 
     for(int x = 0; x < pictureObj.getWidth(); x++)    
     { 
      targetPixel = pictureObj.getPixel(x,y);     
      pixelColor = targetPixel.getColor();      

      redValue = pixelColor.getRed();       
      greenValue = pixelColor.getGreen();      
      blueValue = pixelColor.getBlue();      
      pixelColor = new Color(redValue, greenValue, blueValue); 
      targetPixel.setColor(pixelColor);      
     }//end of the inner for loop 
    }//end of the outer for loop 

    pictureObj.explore();           
    pictureObj.write("NewTrunk.jpg");     
    pictureObj.show();            
}//end of main method 
}//end of class 

回答

0

我建议你看看这个问题:convert a RGB image to grayscale Image reducing the memory in java

虽然你的目的不是减少记忆,它应该达到同样的目的。

--edit-- 一个简单的灰度算法就是取红色,绿色和蓝色的平均值。类似于其他职位,你可以这样做:

redValue = pixelColor.getRed();       
greenValue = pixelColor.getGreen();      
blueValue = pixelColor.getBlue(); 
greyValue = (int)((redValue + greenValue + blueValue)/3)     
pixelColor = new Color(greyValue, greeyValue, greyValue); 
targetPixel.setColor(pixelColor); 
+0

问题在于,我还没有学会如何使用BufferedImages。我正在研究一门课程,这是我坚持的任务之一。 –

+0

非常感谢,解决了我的问题。 –

+0

(R + G + B)/ 3是计算灰度图像颜色的一种非常糟糕的方法。 – eldo

0

您需要更改RGB值使其等于灰度。有很多可能的算法。这里是一个:

int gray = (0.2989 * red) + (0.5870 * green) + (0.1140 * blue); 
pixelColor = new Color(gray, gray, gray); 
+0

当我试图用你提供的代码,它不会编译,因为它说,INT灰度值是不兼容的。它说不能从double转换为int –

+0

另外,当我尝试在将它从double变成int后运行它时,它说新颜色应该是红色,绿色和蓝色,并且放置灰色。 –