package xx.convert.util;
import xx.convert.util2.MyDateUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 头像背景图片转换
* @author yyq
*/
public class ImageBgUtil {
public static void main(String[] args) {
//蓝色
String path = "C:\\Users\\Administrator\\Desktop\\1.jpg";
String suffix = path.substring(path.lastIndexOf("."));
String newPath = path.substring(0, path.lastIndexOf(".")) + "_new"+suffix;
String type = "black";
System.out.println(newPath);
long time = execute(path, newPath, type);
String timeString = MyDateUtil.getTimeString(time);
System.out.println(timeString);
}
/**
* 转换底色
* @param oldPath 需要转换的图片路径
* @param newPath 转换后的图片
* @param type 颜色类型
*/
public static long execute(String oldPath, String newPath, String type){
try {
long old = System.currentTimeMillis();
Color color = null;
if(type.equals("blue")){
color = new Color(89, 147, 255);
}else if(type.equals("white")){
color = new Color(255, 255, 255);
}else if(type.equals("yellow")){
color = new Color(255, 188 , 0);
}else if(type.equals("red")){
color = new Color(255, 18, 18);
}else if(type.equals("green")){
color = new Color(27, 255, 0);
}else if(type.equals("black")){
color = new Color(0, 0, 0);
}else{
color = new Color(255,255,255,0);
}
changeBgColor(oldPath, newPath, color,50);
long useTime = System.currentTimeMillis() - old;
return useTime;
}catch (Exception e){
System.out.println("【图片切换底图颜色-异常错误】");
e.printStackTrace();
return -1;
}
}
/**
* 方法描述: 改变背景色
*
* @param path 图片路径
* @param color 要变成的颜色
* @param range 颜色误差范围(取50左右最佳)
*/
private static void changeBgColor(String path, String newPath, Color color, int range) throws IOException {
BufferedImage image;
//读取原图
BufferedImage origin = ImageIO.read(new File(path));
if (BufferedImage.TYPE_4BYTE_ABGR != origin.getType()) {
//转换图片类型
image = new BufferedImage(origin.getWidth(), origin.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
image.createGraphics().drawImage(origin, 0, 0, null);
} else {
image = origin;
}
//边缘背景rgb
int bgRGB = image.getRGB(image.getMinX(), image.getMinY());
// 遍历Y轴的像素
for (int y = image.getMinY(); y < image.getHeight(); y++) {
// 遍历X轴的像素
for (int x = image.getMinX(); x < image.getWidth(); x++) {
int rgb = image.getRGB(x, y);
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
int R = (bgRGB & 0xff0000) >> 16;
int G = (bgRGB & 0xff00) >> 8;
int B = (bgRGB & 0xff);
//颜色误差范围
if (Math.abs(R - r) < range && Math.abs(G - g) < range && Math.abs(B - b) < range) {
image.setRGB(x, y, color.getRGB());
}
}
}
ImageIO.write(image, "png", new File(newPath));
}
}