需要注意 jdk8对PNG的转换有BUG,会很慢.需要升级JDK或者添加JDK9的增强包.
/**
* 给图片指定位置纯色遮挡
*
* @param x 图片要打码区域左上角的横坐标
* @param y 图片要打码区域左上角的纵坐标
* @param width 图片要打码区域的宽度
* @param height 图片要打码区域的高度
* @param color 遮挡颜色
*/
public static void occlusion(InputStream source, OutputStream target,
int x, int y, int width, int height, Color color) throws IOException {
Graphics gs = null;
try {
//读取该图片
BufferedImage bi = ImageIO.read(source);
//复制一份画布,在新画布上作画,因为要用到原来画布的颜色信息
BufferedImage spinImage = new BufferedImage(bi.getWidth(),
bi.getHeight(), BufferedImage.TYPE_INT_RGB);
//3. 绘制马赛克(在指定范围内绘制矩形并填充颜色)
gs = spinImage.getGraphics();
//将老画布内容画到新画布上
gs.drawImage(bi, 0, 0, null);
int xTmp = x;
int yTmp = y;
gs.setColor(color);
gs.fillRect(xTmp, yTmp, width, height);
gs.dispose();
// 保存图片
ImageIO.write(spinImage, SuffixConsts.PNG, target);
}finally {
if (gs != null){
gs.dispose();
}
}
}