SpringBoot上传图片+ 添加文字水印

 



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.6.RELEASE
		 
	
	com.test
	SpringBootWeb
	0.01
	SpringBootWeb

	
		1.8
	

	

		
		
			org.springframework.boot
			spring-boot-starter
			
				
					org.springframework.boot
					spring-boot-starter-logging
				
			
		
		
			org.springframework.boot
			spring-boot-starter-log4j
			1.3.8.RELEASE
		
		

		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-devtools
			runtime
			true
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		


		
		
		
			javax.servlet
			javax.servlet-api
			provided
		
		
			javax.servlet
			jstl
		

		
		
			org.springframework.boot
			spring-boot-starter-tomcat
		
		
			org.apache.tomcat.embed
			tomcat-embed-jasper
			provided
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


 

配置文件:application.properties

#====================================================
spring.application.name: SpringBootWeb
#server
server.port=80
server.servlet.context-path=/


#====================================================
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
# 上传文件大小3M , 默认1M
spring.servlet.multipart.max-file-size= 3145728
spring.servlet.multipart.max-request-size= 3145728

#====================================================
#springboot 整合 mybatis  
#mybatis.mapper-locations=classpath:mapper/**/*.xml
#mybatis.type-aliases-package=com.mhcloud.manage.**.domain

#====================================================
#dataSource	数据源
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.driverClassName = com.mysql.jdbc.Driver

#spring.datasource.url = jdbc:mysql://127.0.0.1:3306/tt_db?useUnicode=true&characterEncoding=utf-8
#spring.datasource.username = root
#spring.datasource.password = 123123

log4j.properties

log4j.rootLogger=info,stdout,logfile
#stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%t] [%p]-[%C %M %L]-%m%n
 
#logfile
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=/usr/local/logs/service.log
log4j.appender.logfile.MaxFileSize=128MB
log4j.appender.logfile.MaxBackupIndex=100
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} [%t] [%p]-[%C %M %L]-%m%n

 

package com.test.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String watermarkTest(MultipartFile image) throws IOException {
		
		String originalFilename = image.getOriginalFilename();
		String typeName = originalFilename.substring(originalFilename.indexOf(".")+1 ,originalFilename.length()) ;
		
		InputStream inputStream = image.getInputStream();
		OutputStream outputStream = new FileOutputStream("d://adb."+typeName) ;
		
		WaterMarkUtil.markImageByIO("hello world", inputStream, outputStream, 0, typeName);
		
		outputStream.close();
		inputStream.close();
		
		return "redirect:/success.jsp" ;
		
	}
	
	
}

 

package com.test.controller;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

/** 
 *   图片水印工具类
 * 
 */
public class WaterMarkUtil {

	// 水印透明度
	private static float alpha = 0.3f;
	// 水印横向位置
	private static int positionWidth = 50;
	// 水印纵向位置
	private static int positionHeight = 100;
	// 水印文字字体
	private static Font font = new Font("宋体", Font.BOLD, 20);
	// 水印文字颜色
	private static Color color = Color.red;

	/**
	 * 给图片添加水印文字
	 * 
	 * @param text   水印文字
	 * @param srcImgPath 源图片路径
	 * @param targetPath 目标图片路径
	 */
	public static void markImage(String text, String srcImgPath, String targetPath) {
		markImage(text, srcImgPath, targetPath, null);
	}

	/**
	 * 给图片添加水印文字、可设置水印文字的旋转角度
	 * 
	 * @param text
	 * @param srcImgPath
	 * @param targetPath
	 * @param degree
	 */
	public static void markImage(String text, String srcImgPath, String targetPath, Integer degree) {

		OutputStream os = null;
		try {
			// 0、图片类型
			String type = srcImgPath.substring(srcImgPath.indexOf(".") + 1, srcImgPath.length());

			// 1、源图片
			Image srcImg = ImageIO.read(new File(srcImgPath));

			int imgWidth = srcImg.getWidth(null);
			int imgHeight = srcImg.getHeight(null);

			BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

			// 2、得到画笔对象
			Graphics2D g = buffImg.createGraphics();
			// 3、设置对线段的锯齿状边缘处理
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
			// 4、设置水印旋转
			if (null != degree) {
				g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
			}
			// 5、设置水印文字颜色
			g.setColor(color);
			// 6、设置水印文字Font
			g.setFont(font);
			// 7、设置水印文字透明度
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			// 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)

			g.drawString(text, positionWidth, positionHeight);
			// 9、释放资源
			g.dispose();
			// 10、生成图片
			os = new FileOutputStream(targetPath);
			// ImageIO.write(buffImg, "JPG", os);
			ImageIO.write(buffImg, type.toUpperCase(), os);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != os)
					os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 给图片添加水印文字、可设置水印文字的旋转角度
	 * 
	 * @param text
	 * @param srcImgPath
	 * @param targetPath
	 * @param degree
	 */
	public static void markImageByIO(String text, InputStream inputStream, OutputStream outputStream,
			Integer degree, String typeName) {
		try {
			// 1、源图片
			Image srcImg = ImageIO.read(inputStream);

			int imgWidth = srcImg.getWidth(null);
			int imgHeight = srcImg.getHeight(null);
			BufferedImage buffImg = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);

			// 2、得到画笔对象
			Graphics2D g = buffImg.createGraphics();
			// 3、设置对线段的锯齿状边缘处理
			g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			g.drawImage(srcImg.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), 0, 0, null);
			// 4、设置水印旋转
			if (null != degree) {
				g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
			}
			// 5、设置水印文字颜色
			g.setColor(color);
			// 6、设置水印文字Font
			g.setFont(font);
			// 7、设置水印文字透明度
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			// 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)

			g.drawString(text, positionWidth, positionHeight);
			// 9、释放资源
			g.dispose();
			// 10、生成图片
			ImageIO.write(buffImg, typeName.toUpperCase(), outputStream);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String srcImgPath = "d:/002.png";
		String text = "hello world";

		String targerTextPath = "d:/002--1.png";
		String targerTextPath2 = "d:/002--2.png";

		System.out.println("给图片添加水印文字开始...");
		// 给图片添加水印文字
		markImage(text, srcImgPath, targerTextPath);
		// 给图片添加水印文字,水印文字旋转-45
		markImage(text, srcImgPath, targerTextPath2, -45);
		System.out.println("给图片添加水印文字结束...");

	}

}

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
	String path = request.getContextPath() ;
%>    




Insert title here



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
	String path = request.getContextPath() ;
%>    




Insert title here



success  .......


 

SpringBoot上传图片+ 添加文字水印_第1张图片

 

原图: 

SpringBoot上传图片+ 添加文字水印_第2张图片

 

水印图:(浅浅的水印hello world), 尺寸大小不会变化, 大小一般浮动10KB左右

SpringBoot上传图片+ 添加文字水印_第3张图片

 

 

你可能感兴趣的:(SpringBoot)