UI请假,没有PS,需要修改图片中所有绿色为蓝色。于是写了一个代码来处理
MyImageFactory .java
package com.can.lib;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class MyImageFactory {
public interface Callback {
default int colorCallback(int x, int y, int a, int r, int g, int b) {
return 1;
}
default int colorCallback(int a, int r, int g, int b) {
return getColor(a, r, g, b);
}
default int colorCallback(int x, int y, int width, int height, int a, int r, int g, int b) {
return 1;
}
}
public static int getColor(int a, int r, int g, int b) {
return a << 24 | r << 16 | g << 8 | b;
}
public static void createNewImage(File originFile, File targeFile, Callback callback) {
if (!originFile.exists()) {
System.out.println("originFile not exits " + originFile.getAbsolutePath());
return;
}
try {
BufferedImage originImage = ImageIO.read(originFile);
int width = originImage.getWidth();
int height = originImage.getHeight();
BufferedImage targeImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
int color, a, r, g, b;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
color = originImage.getRGB(x, y);
a = color >> 24 & 0xff;
r = color >> 16 & 0xff;
g = color >> 8 & 0xff;
b = color & 0xff;
int newColor = callback.colorCallback(x, y, a, r, g, b);
if (newColor == 1) {
newColor = callback.colorCallback(x, y, width, height, a, r, g, b);
}
if (newColor == 1) {
newColor = callback.colorCallback(a, r, g, b);
}
targeImage.setRGB(x, y, newColor);
}
}
ImageIO.write(targeImage, "png", targeFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用:
ARGB中GB互相替换,绿色显示蓝色
File originFile = new File("lib", "test.png");
MyImageFactory.createNewImage(originFile, new File("lib", "test1.png"), new MyImageFactory.Callback() {
@Override
public int colorCallback(int a, int r, int g, int b) {
int color = MyImageFactory.getColor(a, r, g, b);
if (color != 0xFFFFFFFF) {
r = 255 - r;
g = 255 - g;
b = 255 - b;
}
return MyImageFactory.getColor(a, r, g, b);
}
});