JAVA 实现上传图片添加水印(详细版)
- 经验分享
- 时间:2023-10-07 13:38
- 2064人已阅读
简介
水印的工具类: import javax.imageio.ImageIO;import java.awt.AlphaComposite;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.Rende
🔔🔔🔔好消息!好消息!🔔🔔🔔
有需要的朋友👉:联系凯哥
水印的工具类:
import javax.imageio.ImageIO; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; /** * 定义文字加水印 */ public class ImageWatermarkUtils { // 水印字体 private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 14); // 透明度 private static final AlphaComposite COMPOSITE = AlphaComposite .getInstance(AlphaComposite.SRC_OVER, 0.6f); // 水印之间的间隔 private static final int X_MOVE = 150; // 水印之间的间隔 private static final int Y_MOVE = 200; /** * 打水印(文字) * * @param srcImgPath 源文件地址 * @param font 字体 * @param markContentColor 水印颜色 * @param waterMarkContent 水印内容 * @param outImgPath 输出文件的地址 */ public static void markWithContent(String srcImgPath, Font font, Color markContentColor, String waterMarkContent, String outImgPath) { FileOutputStream fos = null; try { // 读取原图片信息 File srcFile = new File(srcImgPath); File outFile = new File(outImgPath); BufferedImage srcImg = ImageIO.read(srcFile); // 图片宽、高 int imgWidth = srcImg.getWidth(); int imgHeight = srcImg.getHeight(); // 图片缓存 BufferedImage bufImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); // 创建绘图工具 Graphics2D graphics = bufImg.createGraphics(); // 画入原始图像 graphics.drawImage(srcImg, 0, 0, imgWidth, imgHeight, null); // 设置水印颜色 graphics.setColor(markContentColor); // 设置水印透明度 graphics.setComposite(COMPOSITE); // 设置倾斜角度 graphics.rotate(Math.toRadians(-35), (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2); // 设置水印字体 graphics.setFont(font); // 消除java.awt.Font字体的锯齿 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int xCoordinate = -imgWidth / 2, yCoordinate; // 字体长度 int markWidth = FONT.getSize() * getTextLength(waterMarkContent); // 字体高度 int markHeight = FONT.getSize(); // 循环添加水印 while (xCoordinate < imgWidth * 1.5) { yCoordinate = -imgHeight / 2; while (yCoordinate < imgHeight * 1.5) { graphics.drawString(waterMarkContent, xCoordinate, yCoordinate); yCoordinate += markHeight + Y_MOVE; } xCoordinate += markWidth + X_MOVE; } // 释放画图工具 graphics.dispose(); // 输出图片 fos = new FileOutputStream(outFile); ImageIO.write(bufImg, "jpg", fos); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } } } //计算水印文本长度 //1、中文长度即文本长度 2、英文长度为文本长度二分之一 public static int getTextLength(String text) { //水印文字长度 int length = text.length(); for (int i = 0; i < text.length(); i++) { String s = String.valueOf(text.charAt(i)); if (s.getBytes().length > 1) { length++; } } length = length % 2 == 0 ? length / 2 : length / 2 + 1; return length; } public static void main(String[] args) { ImageWatermarkUtils.markWithContent("J:\\apache-tomcat-7.0.52\\webapps\\uploadimage\\aftersale\\202211071412117038f330-a850-469d-92f3-937f174bfa49.jpg", FONT, Color.darkGray, "ls65535", "J:\\apache-tomcat-7.0.52\\webapps\\uploadimage\\aftersale\\202211071412117038f330-a850-469d-92f3-937f174bfa49.jpg"); } }
Controller层
import com.lt.crm.common.QsMap; import com.lt.crm.common.util.ImageWatermarkUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.Color; import java.awt.Font; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.UUID; @CrossOrigin @RestController @RequestMapping("/UploadFileImage") @Api(value = "图片", tags = "微信小程序~图片加水印") public class CustomUploadFileController { private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 14); /** * WeChat 微信小程序 图片上传 * @param request * @param response * @return * @throws IOException */ @ApiOperation(value = "图片上传",notes = "UploadPic") @RequestMapping(value = "/images", method = {RequestMethod.POST, RequestMethod.GET}) public QsMap uploadPicture(HttpServletRequest request, HttpServletResponse response) throws IOException { QsMap qsMap = new QsMap(); //获取上传文件的主文件名与扩展名 MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; //对应前端的upload的name参数"file" MultipartFile multipartFile = req.getFile("file"); //获取上传时的名称 String fileName = multipartFile.getOriginalFilename(); //存放图片的绝对路径 String realPath = "J:\\apache-tomcat-7.0.52\\webapps\\uploadimage\\aftersale"; //格式化时间戳 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); //System.currentTimeMillis() 是直接调用本地方法,而 new Date().getTime() 确还要创建一个Date对象,降低了效率和占用了内存(虽然损耗很小)。 String nowTime = sdf.format(System.currentTimeMillis()); //取得图片的格式后缀 String originalLastName = multipartFile.getOriginalFilename(); String picLastName = originalLastName.substring(originalLastName.lastIndexOf(".")); //判断上传格式 if(picLastName.equals(".jpg") || picLastName.equals(".gif") || picLastName.equals(".png") || picLastName.equals(".jpeg")){ try { File dir = new File(realPath); //如果文件目录不存在,创建文件目录 if (!dir.exists()) { dir.mkdirs(); } //拼接 名字+时间戳+后缀 String picName = nowTime + UUID.randomUUID() + picLastName; File file = new File(realPath,picName); multipartFile.transferTo(file); //全路径 qsMap.put("file","J:\\apache-tomcat-7.0.52\\webapps\\uploadimage\\aftersale\\" + picName); //获取上传的图片路径 加水印(尺寸~大小~样式/工具类自行调节) ImageWatermarkUtils.markWithContent((String) qsMap.get("file"), FONT, Color.darkGray, "ls65535", (String) qsMap.get("file")); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } }else{ qsMap.put("上传了不合法的图片后缀!",picLastName); } return qsMap; } }
PostMan测试:
效果:
其他:
https://blog.csdn.net/lv5751394/article/details/107220155
https://blog.csdn.net/qq_26383975/article/details/125996277
https://blog.csdn.net/YangRunkangBla/article/details/50511955