2016-07-29 51 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後運行它時,它說新顏色應該是紅色,綠色和藍色,並且放置灰色。 –