上代码
// @水印图片 水印图片地址
@Setter
@Getter
private static String iconPath = "https://www.lgstatic.com/i/audio1/M00/07/BA/CgHIk161EjGAXn6MAAAKzcmgVoA583.png";
private static int standardWidth = 750;
/**
* 添加图片水印
* 水印固定为 @水印图片 角标
* @param srcFile
* @return
*/
public static File addWaterMark(File srcFile) {
OutputStream os = null;
try {
// 源图片
String formatName = FileType.getSuffixByFilename(srcFile.getName()).substring(1);
Image srcImg = ImageIO.read(srcFile);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
int srcImgWidth = buffImg.getWidth(); // 图片宽
int srcImgHeight = buffImg.getHeight(); // 图片高
// 1、得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 2、设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
// 3、画原图
g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1.0f));
// 4、水印图片的路径 水印图片一般为gif或者png的,这样可设置透明度
InputStream in = getImageStream(iconPath);
if (in == null) {
log.warn("iconPath 获取网络图片失败: " + iconPath);
return srcFile;
}
// 5、得到Image对象
BufferedImage imgIconBufferedImage = ImageIO.read(in);
ImageIcon imgIcon = new ImageIcon(imgIconBufferedImage);
// 标准尺寸边距是 20px 标准图片大小 750 比例缩放
int margin = scale(10, srcImgWidth);
int width = scale(imgIcon.getIconWidth(), srcImgWidth);
int height = scale(imgIcon.getIconHeight(), srcImgWidth);
int positionX = srcImgWidth - width - margin ;
int positionY = srcImgHeight - height - margin ;
// 6、水印图片的位置
g.drawImage(imgIconBufferedImage, positionX, positionY, width, height,null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// 7、释放资源
g.dispose();
// 8、生成图片
os = new FileOutputStream(srcFile.getAbsolutePath());
ImageIO.write(buffImg, formatName, os);
} catch (Exception e) {
log.error("Exception" , e);
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e) {
log.error("close Exception" , e);
}
}
return srcFile;
}
private static int scale(int w, int srcImgWidth) {
return (w * srcImgWidth) / standardWidth;
}
/**
* 获取网络图片流
*
* @param url
* @return
*/
private static InputStream getImageStream(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
log.error("获取网络图片出现异常,图片路径为:" + url, e);
}
return null;
}
来源:oschina
链接:https://my.oschina.net/zz006/blog/4271955