引言:
最近有给图片添加水印的需求,于是找了Thumbnailator工具;Thumbnailator中可以方便的对图片增加图片水印,但是在添加文字水印上却没有方法。
版本一(未使用Thumbnailator依赖):
/*** @author:kuqi* @createTime:2022/1/26 11:13* @description:*/
public class ImageUtil {/*** 图片添加水印** @param srcImgPath 需要添加水印的图片的路径* @param outImgPath 添加水印后图片输出路径* @param waterMark 水印的文字*/public static void mark(String srcImgPath, String outImgPath, String waterMark) {try {// 读取原图片信息File srcImgFile = new File(srcImgPath);Image srcImg = ImageIO.read(srcImgFile);int srcImgWidth = srcImg.getWidth(null);int srcImgHeight = srcImg.getHeight(null);// 初始化画布,图片多大,画布多大BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g = bufImg.createGraphics();//指定要绘制的图片g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);double fontLength = srcImgWidth * 0.3;//根据比例设置文字占的长度,即文字长度int fontSize = (int) (fontLength / 5 * 0.9);//文字大小,0.9为差值//设置字体样式,加粗,大小Font font = new Font("微软雅黑", Font.BOLD, fontSize);//设置文字颜色g.setColor(Color.BLACK);g.setFont(font);//绘制文字的横纵坐标int x = (int) (srcImgWidth - fontLength - 3);int y = srcImgHeight - fontSize - 3;//绘制文字水印g.drawString(waterMark, x, y);g.dispose();// 输出图片FileOutputStream outImgStream = new FileOutputStream(outImgPath);ImageIO.write(bufImg, "jpg", outImgStream);outImgStream.flush();outImgStream.close();} catch (Exception e) {e.printStackTrace();}}}
实例效果
版本二(使用Thumbnailator依赖,以流的形式对图片进行处理)
/*** 添加文字水印* @param bytes //图片的字节数组* @param waterText //文字水印* @param opacity //水印的不透明度度,1不透明~0透明* @param width //水印的高度* @param height //水印的宽度* @return //Graphics2D中rotate方法设置文字的的倾斜度*/public static byte[] addTextWater(byte[] bytes, String waterText, int width, int height, float opacity) {InputStream in = null;ByteArrayOutputStream bout = null;try {in = new ByteArrayInputStream(bytes);bout = new ByteArrayOutputStream(1024);// 将画布大小绘制成原图大小BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//创建一个graphics2d,用于绘制BufferedImageGraphics2D g = bi.createGraphics();//清除矩形区域g.clearRect(0, 0, width, height);// 设置绘图区域透明bi = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);g.dispose();g = bi.createGraphics();// 设置字体类型、大小、加粗、颜色、旋转度(未使用)double fontLength = width*0.3; //文字的长度,按比例给定int fontSize = (int) (fontLength/5*0.9); //文字的大小,5表示多少个字儿,0.9为差值//字体颜色g.setColor(new Color(0, 0, 0));Font font = new Font("微软雅黑", Font.BOLD, fontSize);g.setFont(font);//绘制文字的横纵坐标,其位置是在图片的右下角int x = (int) (width - fontLength + 3); //3为差值,可以自调int y = height - (fontSize/2) + 7; //7补个差值,可以自调//填充文字在画布上g.drawString(waterText, x, y);//结束绘画g.dispose();Thumbnails.of(in).scale(1).watermark(Positions.CENTER, bi, opacity).toOutputStream(bout);return bout.toByteArray();} catch (Exception ex) {throw new RuntimeException(ex);} finally {try {if (in != null) {in.close();}if (bout != null) {bout.close();}} catch (Exception ex) {ex.printStackTrace();}}}
实例效果
参考文献
https://www.cnblogs.com/qlqwjy/p/9326468.html
https://blog.csdn.net/zengchao9/article/details/84744236