[英]how to tint a black and white .png image to a certain color in Java
我有一个 .png 图像,我需要使用 RGB 值 207、173、23 为自定义颜色着色。( https://github.com/pret/pokecrystal/blob/master/gfx/tilesets/players_room.png?原始=真)
我做了一些研究,发现了以下代码:
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 值的缓冲图像。 但是,每当我使用它时,它只会返回没有颜色的较亮或较暗版本的图像。 我想知道问题是否出在图像本身,可能与透明度有关,还是代码的问题?
问题是 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.