首页 > 解决方案 > 更改缓冲图像背景

问题描述

我正在尝试创建一个徽标大小调整器,它还会根据用户输入将徽标背景的颜色更改为白色或透明。

这可以将图像的背景颜色从透明变为白色:

    BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); //reads the input image
    BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.TYPE_INT_ARGB); //creates the output image

    Graphics2D image = outputImage.createGraphics(); 
    image.setBackground(Color.WHITE);    //sets background color to white
    image.fillRect(0, 0, newWidth, newHeight);
    image.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
    image.dispose();

    String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1); //Finds what type of image it is

    ImageIO.write(outputImage, formatName, new File(outputImagePath)); //Creates the output image file in correct path
}

我想如果我把它改成这个,它会将图像背景颜色从白色更改为透明,但它会保持白色。有什么帮助吗?

    BufferedImage inputImage = ImageIO.read(new File(inputImagePath)); //reads the input image
    BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.TYPE_INT_ARGB); //creates the output image

    Graphics2D image = outputImage.createGraphics(); //Draws the actual output image
    image.setComposite(AlphaComposite.Clear);
    image.fillRect(0, 0, newWidth, newHeight);
    image.setComposite(AlphaComposite.Src);
    image.drawImage(inputImage, 0, 0, newWidth, newHeight, null);   //Draws the actual output image
    image.dispose();

    String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1); //Finds what type of image it is

    ImageIO.write(outputImage, formatName, new File(outputImagePath)); //Creates the output image file in correct path
}

我现在在想,我可能必须追踪徽标并为其本身赋予一个全新的背景,但这可能会非常困难。有什么建议吗?

标签: javagraphicsbackgroundbufferedimagetransparent

解决方案


推荐阅读