我在用透明像素转换成灰度的彩色图像时遇到了问题。我在这个网站上搜索并找到了相关的问题,但是没有任何东西可以用来解决我的问题。
我定义了一个方法"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);
}
}
我从一个名为“BufferedImage”的TYPE_4BYTE_ABGR
类型的TYPE_4BYTE_ABGR
开始,然后:
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算法,我就可以解决这个问题。我已经下载了源代码,并四处搜寻,但一直未能找到算法。如果有人能这样做,我将非常感激:
发布于 2018-03-06 18:50:19
由于只有BITMASK支持透明性,所以首先使用TYPE_BYTE_GRAY将图像转换为TYPE_BYTE_GRAY,然后使用BITMARK将图像转换为具有透明度。希望这能有所帮助。我也遇到了同样的问题--我用了这个方法。
//grey scale image
BufferedImage b = new BufferedImage(
colorImage.getWidth(),
colorImage.getHeight(),
BufferedImage.TYPE_BYTE_GRAY);
File lostFGFile = new File(lostFgFileName);
Graphics g = b.createGraphics();
g.drawImage(colorImage, 0, 0, null);
g.setColor(Color.gray);
ImageIO.write(b, "png", lostFGFile);
g.dispose();
//convert the lost image as transparent
BufferedImage greyImage = ImageIO.read(new FileInputStream(lostFgFileName));
b = new BufferedImage(
colorImage.getWidth(),
colorImage.getHeight(),
BufferedImage.BITMASK);
g = b.createGraphics();
g.drawImage(greyImage, 0, 0, null);
ImageIO.write(b, "png", lostFGFile);
g.dispose();
https://stackoverflow.com/questions/21176754
复制相似问题