直接上代码:
-
图片压缩加水印
@Test public void TetsShuiYin() { // String path1 = "D:\\temp\\Flower.PNG"; // String path1 = "D:\\temp\\A@00171289834389489523G0023_1612888117303.png"; String path1 = "D:\\temp\\微信图片_20210507102616.jpg"; String path2 = "D:\\temp\\image\\" + System.currentTimeMillis() + ".jpg"; String[] strings = new String[3]; strings[0] = "主任务号:922104113414345"; strings[1] = "子任务号:12345678765432345"; strings[2] = "上传时间:2021-04-21 17:23:09"; byte[] a = generateText(strings, path1, "宋体", 28, Color.RED, Font.PLAIN); try { assert a != null; byte2image(a, path2); } catch (AssertionError e) { System.out.println("shuchu"); } } /** * 添加文字水印的方法 * * @param pressText 要添加的文字 * @param path 文件路径,这里只处理了了本地文件,未处理网络图片 * @param fontName 文字的字体名称 * @param fontSize 文字的大小 * @param fontColor 文字的眼神 * @param style 文字的格式,如Font.BOLD++Font.ITALIC表示粗体斜体 * @return */ private static byte[] generateText(String[] pressText, String path, String fontName, int fontSize, Color fontColor, int style) { if (pressText.length < 1) { return new byte[0]; } try { BufferedImage bgImage = ImageIO.read(new FileInputStream(new File(path))); int wideth = bgImage.getWidth(); int height = bgImage.getHeight(); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(bgImage, 0, 0, wideth, height, null); /* 消除java.awt.Font字体的锯齿 */ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //设置字体大小、颜色等 g.setColor(fontColor); Font font = new Font("宋体", Font.PLAIN, fontSize); g.setFont(font); double x1 = wideth / fontSize; double x2 = pressText[0].length() / x1; double beginX = wideth - (wideth * x2); double y1 = height / fontSize; //能放多少个字 System.out.println("height " + height); System.out.println("y1 " + y1); for (int i = 0; i < pressText.length; i++) { //字体默认放在右下角 根据图片自适应 double s = (i + 1)*fontSize; double h = height -s; g.drawString(pressText[i], (int) beginX, (int) h); } g.dispose(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", out); return out.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将字节数组转换为本地图片 * * @param data * @param path */ public static void byte2image(byte[] data, String path) { if (data.length < 3 || path.equals("")) { return; } try { FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path)); imageOutput.write(data, 0, data.length); imageOutput.close(); System.out.println("生成图片成功:" + path); } catch (Exception ex) { ex.printStackTrace(); } }