首先晒出图片的绘制效果,(哈哈,本网站水映有点重合,但不这不是重点!!) 下面就晒出自己的代码。。。 public static InputStream getMark(List<String> words, Color color, InputStream inputStream) throws IOException { ByteArrayOutputStream os = null; InputStream input = null; try { BufferedImage read = ImageIO.read(inputStream);//将文件流转为可操作的Buffer Graphics2D g2 = read.createGraphics();//拿到绘图对象 g2.drawImage(read, 0, 0, read.getWidth(null), read.getHeight(null), null);//绘制以确定的图片 Font font = new Font("微软雅黑", Font.BOLD, 20); g2.setColor(color); g2.setFont(font); for(int i=0;i<words.size();i++){ int x = read.getWidth(null) - getWatermarkLength(words.get(i), g2)-20; int y = read.getHeight(null) - 25*(i+1); g2.drawString(words.get(i), x, y); } g2.dispose();//释放绘制对象 os = new ByteArrayOutputStream();//声明一个字节数组输出流 ImageIO.write(read, "png", os);//将BUfferImage写入数组流中 input = new ByteArrayInputStream(os.toByteArray());//转回inputStream } catch (Exception e) { log.info(e.getMessage()); }finally { if(os!=null){ os.flush(); os.close(); } } return input; } public static int getWatermarkLength(String waterMarkContent, Graphics2D g) { return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length()); }
java给图片加水印
最新推荐文章于 2024-06-29 16:01:21 发布