Skip to content

Instantly share code, notes, and snippets.

@nickkeers
Created September 20, 2014 14:50
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 nickkeers/e20f1c8b8788eb60c41e to your computer and use it in GitHub Desktop.
Save nickkeers/e20f1c8b8788eb60c41e to your computer and use it in GitHub Desktop.
A program that converts the supplied image to grayscale using the lightness algorithm. Made quickly for /r/dailyprogrammer challenge 179
package javagrayscaler;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class JavaGrayscaler
{
static String filePath = "";
static int lightness(int r, int g, int b)
{
int max = Math.max(r, Math.max(g,b));
int min = Math.min(r, Math.min(g,b));
return (max+min)/2;
}
public static BufferedImage imageToGrayscale(BufferedImage image)
{
BufferedImage img = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
int clr = image.getRGB(x, y);
int r = (clr & 0x00ff0000) >> 16;
int g = (clr & 0x0000ff00) >> 8;
int b = clr & 0x000000ff;
int grayLevel = lightness(r,g,b);
int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel;
img.setRGB(x, y, gray);
}
}
return img;
}
public static void main(String[] args)
{
if(args.length != 1)
{
System.out.println("No file supplied as argument, terminating");
System.exit(0);
}
else
{
filePath = args[0];
File f = new File(filePath);
try
{
System.out.println("Starting conversion...");
BufferedImage image = ImageIO.read(f);
BufferedImage converted = imageToGrayscale(image);
String ext = f.getPath().substring(f.getPath().lastIndexOf("."));
ImageIO.write(converted, "png", new File("gray" + ext));
System.out.println("Converted");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment