Skip to content

Instantly share code, notes, and snippets.

@elvismdev
Last active January 5, 2016 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvismdev/e81eebb7a2769b8612e6 to your computer and use it in GitHub Desktop.
Save elvismdev/e81eebb7a2769b8612e6 to your computer and use it in GitHub Desktop.
A Java small class to convert colorful images into grayscale. The library edu.duke is a dependency for the class to work, it should be added into the Java IDE to compile with no errors. Download link http://www.dukelearntoprogram.com/downloads/archives/courserajava.jar
/**
* Create a gray scale version of an image by setting all color components of each pixel to the same value.
*/
import edu.duke.*;
import java.io.File;
public class GrayScaleConverter {
//I started with the image I wanted (inImage)
public ImageResource makeGray(ImageResource inImage) {
//I made copy of the original image with color which will be the one later returned in grayscale
ImageResource outImage = new ImageResource(inImage);
//for each pixel in outImage
for (Pixel pixel: outImage.pixels()) {
//look at the corresponding pixel in inImage
Pixel inPixel = inImage.getPixel(pixel.getX(), pixel.getY());
//compute inPixel's red + inPixel's blue + inPixel's green
//divide that sum by 3 (call it average)
int average = (inPixel.getRed() + inPixel.getBlue() + inPixel.getGreen()) /3;
//set pixel's red to average
pixel.setRed(average);
//set pixel's green to average
pixel.setGreen(average);
//set pixel's blue to average
pixel.setBlue(average);
}
//outImage is your answer
return outImage;
}
public void selectConvertAndSave() {
DirectoryResource dr = new DirectoryResource();
for (File f : dr.selectedFiles()) {
ImageResource inImage = new ImageResource(f);
ImageResource gray = makeGray(inImage);
gray.setFileName("gray-" + inImage.getFileName());
gray.draw();
gray.save();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment