首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在不丢失透明度的情况下将图像转换为灰度?

如何在不丢失透明度的情况下将图像转换为灰度?
EN

Stack Overflow用户
提问于 2014-01-17 02:25:54
回答 4查看 3.4K关注 0票数 3

我在用透明像素转换成灰度的彩色图像时遇到了问题。我在这个网站上搜索并找到了相关的问题,但是没有任何东西可以用来解决我的问题。

我定义了一个方法"convertType“如下:

代码语言:javascript
运行
复制
/*------------------------------
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开始,然后:

代码语言:javascript
运行
复制
 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. 建议另一种方法来完成我想要做的事情。
EN

Stack Overflow用户

发布于 2018-03-06 18:50:19

由于只有BITMASK支持透明性,所以首先使用TYPE_BYTE_GRAY将图像转换为TYPE_BYTE_GRAY,然后使用BITMARK将图像转换为具有透明度。希望这能有所帮助。我也遇到了同样的问题--我用了这个方法。

代码语言:javascript
运行
复制
//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();
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21176754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档