如何在Java中将黑白.png图像着色为特定颜色

时间:2020-03-21 22:22:17

标签: java image-processing

我有一个.png图像,我需要用207、173、23的RGB值设置自定义颜色。(https://github.com/pret/pokecrystal/blob/master/gfx/tilesets/players_room.png?raw=true

我做了一些研究,发现以下代码:

public BufferedImage getBufferedImage(String source, int redPercent, int greenPercent, int bluePercent) throws IOException{
    BufferedImage img = null;
    File f = null;

    try{
        f = new File(source);
        img = ImageIO.read(f);
    }catch(IOException e){
        System.out.println(e);
    }

    int width = img.getWidth();
    int height = img.getHeight();

    for(int y = 0; y < height; y++){
        for(int x = 0; x < width; x++){
            int p = img.getRGB(x,y);

            int a = (p>>24)&0xff;
            int r = (p>>16)&0xff;
            int g = (p>>8)&0xff;
            int b = p&0xff;

            p = (a<<24) | (redPercent*r/100<<16) | (greenPercent*g/100<<8) | (bluePercent*b/100);

            img.setRGB(x, y, p);
        }
    }

    return img;
}

该方法应返回具有输入RGB值的缓冲图像。但是,每当我使用它时,它只会返回浅色的较暗版本的图像,而没有颜色。我想知道问题是否出在图像本身上,也许与透明度有关,还是问题出在代码上?

1 个答案:

答案 0 :(得分:1)

问题在于PNG图像设置为仅容纳灰度数据,因此BufferedImage img也仅能够容纳灰度数据。要解决此问题,只需在RGB颜色模式下创建一个输出BufferedImage。

我还整理了您的异常处理。

import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;


class SOQuestion {
    public static BufferedImage getBufferedImage(String source,
            int redPercent, int greenPercent, int bluePercent) {
        BufferedImage img = null;
        File f = null;

        try {
            f = new File(source);
            img = ImageIO.read(f);
        } catch (IOException e) {
            System.out.println(e);
            return null;
        }

        int width = img.getWidth();
        int height = img.getHeight();
        BufferedImage out = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_RGB);

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int p = img.getRGB(x,y);

                int a = (p>>24) & 0xff;
                int r = (p>>16) & 0xff;
                int g = (p>>8) & 0xff;
                int b = p & 0xff;

                p = (a<<24) | (redPercent*r/100<<16) |
                    (greenPercent*g/100<<8) | (bluePercent*b/100);

                out.setRGB(x, y, p);
            }
        }

        return out;
    }

    public static void main(String[] args) {
        BufferedImage result = SOQuestion.getBufferedImage(args[0], 81, 68, 9);
        File outputfile = new File("output.png");
        try {
            ImageIO.write(result, "png", outputfile);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}