Ben Rocco Ben Rocco - 4 months ago 16
Java Question

Grayscale on Picture using Java

I am so lost for this code I am working on. I have to make a picture have a grayscale using only java. I have the base code, but I do not know what to put in that won't make the entire screen gray. I am avidly working on it, but I am lost and have no clue what to do next. The way it currently is, it just takes an image goes through a process then makes a new version of it completely the same, but I need to make the new version the grayed version of it.
Visit: https://ask.extension.org/uploads/question/images/attachments/000/037/087/image_300x300%2523.jpg?1406470060 For the tree picture I am using.

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

Answer

I suggest you check out this question: convert a RGB image to grayscale Image reducing the memory in java.

While your intention is not to reduce memory, it should serve the same purpose.

--edit-- A simple greyscale algorithm is simply to take the average of the red, green, and blue. Similar to the other post you could do:

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