I am having problems converting a colored image with some transparent pixels to grayscale. I have searched and found related questions on this website but nothing I have been able to use to solve my problem.
I have defined a method "convertType" as follows:
/*------------------------------
attempts to convert the type of the image argument to the chosen type
for example: BufferedImage newImage= ImageUtilities.convertType(oldImage, BufferedImage.TYPE_3BYTE_BGR);
11/28/2013 WARNING-it remains to be seen how well this method will work for various type conversions
------------------------------*/
public static BufferedImage convertType (BufferedImage image,int newType){
if (image.getType() == newType){
return (image);
}else {
int w= image.getWidth();
int h= image.getHeight ();
BufferedImage modifiedImage = new BufferedImage( w,h,newType);
Graphics2D g = ( Graphics2D)modifiedImage.getGraphics();
g.drawImage( image, null, 0,0);
g.dispose();
return (modifiedImage);
}
}
I start with a BufferedImage of type TYPE_4BYTE_ABGR
named "result", then:
result= convertType (result, BufferedImage.TYPE_BYTE_GRAY);//transparency is lost
result=convertType (result, BufferedImage.TYPE_INT_ARGB);//pixels will now support transparency
For colored opaque pixels in the original image the above sequence works fine: for example, (32, 51, 81, 255)-> (49, 49, 49, 255)
However, transparent pixels in the original image are turned opaque: for example, (0, 0, 0, 0)-> (0, 0, 0, 255)
I understand what is happening and I can work around the problem if I can make use of the Java algorithm used to convert to grayscale. I have downloaded the source code and poked around but have not been able to locate the algorithm. I would greatly appreciate it if someone could either:
- tell me what class contains the grayscale conversion algorithm or
- suggest an alternative way to accomplish what I am trying to do.