//区分普通/avatar头像
String type = "avatar";
//目标文件(嵌入图片)
String pressImg = "https://image.fprice.cn/boot-admin/api/common/view/static/icon_mini_logo.png";
//主图片
String targetImg = "C:\\Users\\Administrator\\Desktop\\img\\199ba2abb7a0f7af1c4bcd79bc4b0802.jpeg";
int x = 66 ;
int y = 766;
//x轴偏移距离
int xOffset = 0;
//y轴偏移距离
int yOffset = 40;
//宽度
int pressImgW = 124;
//高度
int pressImgH = 124;
try {
//目标文件
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
//水印文件
Image src_biao = null;
if (pressImg.indexOf("http") > -1) {
URL url = new URL(pressImg);
src_biao = ImageIO.read(url);
} else {
File _filebiao = new File(pressImg);
src_biao = ImageIO.read(_filebiao);
}
int width_biao = pressImgW > 0 ? pressImgW : src_biao.getWidth(null);
int height_biao = pressImgH > 0 ? pressImgH : src_biao.getHeight(null);
int xx = x > 0 ? x : (width - width_biao) / 2 - xOffset;
int yy = y > 0 ? y : (height - height_biao) / 2 - yOffset;
if (type.equals("avatar")) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//留一个像素的空白区域,这个很重要,画圆的时候把这个覆盖
int border = 1;
//图片是一个圆型
Ellipse2D.Double shape = new Ellipse2D.Double(xx, yy, width_biao - border * 2, height_biao - border * 2);
//需要保留的区域
g.setClip(shape);
}
g.drawImage(src_biao, xx, yy, width_biao, height_biao, null);
//水印文件结束
g.dispose();
// FileOutputStream out = new FileOutputStream(targetImg);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// encoder.encode(image);
// out.close();
String formatName = targetImg.substring(targetImg.lastIndexOf(".") + 1);
//覆盖原图
ImageIO.write(image, formatName, new File(targetImg));
} catch (Exception e) {
e.printStackTrace();
}
01-18
7862
03-02
2584