how can I convert an image to grayscale without losing transparency?

前端 未结 4 2041
小鲜肉
小鲜肉 2021-01-14 07:55

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 be

4条回答
  •  星月不相逢
    2021-01-14 08:25

    As only BITMASK support transparency, first convert the image to greyScale using TYPE_BYTE_GRAY, then use BITMARK to convert the image to have transparency. Hope this helps. I had the same problem I used this approach.

    //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();
    

提交回复
热议问题