我很困扰如何将一张有透明像素的彩色图像转换为灰度图。我在这个网站上搜索了相关问题,但没有找到能解决我的问题的答案。
我已定义了一个名为“convertType”的方法,具体内容如下:
/*------------------------------
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);
}
}
我从一个名为“result”的
TYPE_4BYTE_ABGR
BufferedImage开始,然后: result= convertType (result, BufferedImage.TYPE_BYTE_GRAY);//transparency is lost
result=convertType (result, BufferedImage.TYPE_INT_ARGB);//pixels will now support transparency
对于原始图像中的有颜色的不透明像素,以上步骤可以很好地运行: 例如,(32,51,81,255)->(49,49,49,255)
然而,原始图像中的透明像素被变为不透明: 例如,(0,0,0,0)->(0,0,0,255)
我理解正在发生的事情,如果我可以使用Java算法来转换灰度图像,那么我就可以解决问题。我已经下载了源代码并仔细查看,但是还没有找到算法。如果有人可以告诉我:
1. 包含灰度转换算法的类 2. 建议我完成我要做的事情的另一种方法
我将非常感激。