Applying a tint to an image in java

前端 未结 7 805
太阳男子
太阳男子 2020-12-09 16:25

I am trying to create several similar visual styles for my programs, each with a different color theme. To do this, I have implemented the use of icons to represent the diff

7条回答
  •  忘掉有多难
    2020-12-09 16:29

    I tried every solution on this page, had no luck. The Xor one (accepted answer) didn't work for me - tinted a weird yellow color instead of the color I was giving as an argument no matter what the argument. I finally found an approach that works for me, though it is a bit messy. Figured I'd add it in case anyone else is having the same issues I am with the other solutions. Cheers!

    /** Tints the given image with the given color.
     * @param loadImg - the image to paint and tint
     * @param color - the color to tint. Alpha value of input color isn't used.
     * @return A tinted version of loadImg */
    public static BufferedImage tint(BufferedImage loadImg, Color color) {
        BufferedImage img = new BufferedImage(loadImg.getWidth(), loadImg.getHeight(),
                BufferedImage.TRANSLUCENT);
        final float tintOpacity = 0.45f;
        Graphics2D g2d = img.createGraphics(); 
    
        //Draw the base image
        g2d.drawImage(loadImg, null, 0, 0);
        //Set the color to a transparent version of the input color
        g2d.setColor(new Color(color.getRed() / 255f, color.getGreen() / 255f, 
            color.getBlue() / 255f, tintOpacity));
    
        //Iterate over every pixel, if it isn't transparent paint over it
        Raster data = loadImg.getData();
        for(int x = data.getMinX(); x < data.getWidth(); x++){
            for(int y = data.getMinY(); y < data.getHeight(); y++){
                int[] pixel = data.getPixel(x, y, new int[4]);
                if(pixel[3] > 0){ //If pixel isn't full alpha. Could also be pixel[3]==255
                    g2d.fillRect(x, y, 1, 1);
                }
            }
        }
        g2d.dispose();
        return img;
    }
    

提交回复
热议问题