public class BlackWhite {
public static void main(String[] args)
{
try
{
BufferedImage original = ImageIO.read(new File("colorimage"));
BufferedImage binarized = new BufferedImage(original.getWidth(), original.getHeight(),BufferedImage.TYPE_BYTE_BINARY);
int red;
int newPixel;
int threshold =230;
for(int i=0; i<original.getWidth(); i++)
{
for(int j=0; j<original.getHeight(); j++)
{
// Get pixels
red = new Color(original.getRGB(i, j)).getRed();
int alpha = new Color(original.getRGB(i, j)).getAlpha();
if(red > threshold)
{
newPixel = 0;
}
else
{
newPixel = 255;
}
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
binarized.setRGB(i, j, newPixel);
}
}
ImageIO.write(binarized, "jpg",new File("blackwhiteimage") );
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static int colorToRGB(int alpha, int red, int green, int blue) {
int newPixel = 0;
newPixel += alpha;
newPixel = newPixel << 8;
newPixel += red; newPixel = newPixel << 8;
newPixel += green; newPixel = newPixel << 8;
newPixel += blue;
return newPixel;
}
}
我得到了一张黑白输出图像,但是当我放大图像时,我发现了一些灰色区域。我希望输出图像只包含黑色或白色。
请让我知道我目前的方法是正确还是不正确?如果我是,请建议另一种方式。