I am writing a program to apply a color filter to an image. The color filter is described as follows :
My code to achieve such a task is :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package image.processor;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
*
* @author USER PC
*/
public class GrayscaleConverter {
BufferedImage image;
int height;
int width;
File input;
File output;
public GrayscaleConverter(File in,File out)
{
input=in;
output=out;
}
public boolean convertToGrayscale()
{
try
{
image=ImageIO.read(input);
height=image.getHeight();
width=image.getWidth();
int pos_row=0;
int pos_col=0;
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
Color col=new Color(image.getRGB(j, i));
//System.out.println(image.getRGB(j, i));
Color grayscale_color=new Color(1,1,1);
int red=col.getRed();
int blue=col.getBlue();
int green=col.getGreen();
switch(pos_col)
{
case 0 : grayscale_color=new Color(red,0,0);
break;
case 1 : grayscale_color=new Color(0,green,0);
break;
case 2 : grayscale_color=new Color(0,0,blue);
break;
default : System.out.println("Error occoured");
}
//grayscale_color=new Color(red,0,0);
//System.out.println(grayscale_color.getRed()+" "+grayscale_color.getGreen()+ " " +grayscale_color.getBlue() );
image.setRGB(j, i,grayscale_color.getRGB());
pos_col=(pos_col+1)%3;
}
pos_row=(pos_row+1)%3;
pos_col=pos_row;
}
ImageIO.write(image,"jpg",output);
return true;
}
catch(Exception e)
{
System.out.println(e.toString()+"error");
}
return false;
}
void printWrittenColor()
{
try{
image=ImageIO.read(output);
height=image.getHeight();
width=image.getWidth();
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
Color col=new Color(image.getRGB(j,i));
//System.out.println("Red = "+col.getRed()+" Blue = "+col.getBlue()+ "Green = "+col.getGreen());
}
}
}
catch(Exception e){}
}
}
However even if the image looks pretty much as I want it to the colors being read back by my printWrittenColor()
method gives arbitrary color values. It would thus be my guess that there is something wrong in my reading method.
Also my expected output is :
23,0,0
0,2,0
0,0,34
......
However what I get as output is arbitrary values of red , green and blue.
Could you please point me in the right direction ?