java实现图片上加文字水印(SpringMVC + Jsp)

 更新时间:2022年05月06日 15:34:34   作者:wenteryan  
这篇文章主要为大家详细介绍了java实现在图片上加文字水印的方法,水印可以是图片或者文字,操作方便,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

看之前要先对SpringMVC进行了解打好基础,下面直接先看效果图

代码编写

1.导入相关架包

2.配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 <display-name>watermarkspringmvc</display-name>
 <servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 <mvc:default-servlet-handler/>
 <mvc:annotation-driven/> 
 <context:component-scan base-package="com.wenteryan"></context:component-scan>
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/"></property>
  <property name="suffix" value=".jsp"></property>
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
 </bean>

 <bean id="multipartResolver" 
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding" value="UTF-8"></property>
  <property name="maxUploadSize" value="10485760000"></property>
  <property name="maxInMemorySize" value="40960"></property>
 </bean>

</beans>

3.编写action

WatermarkAction .action

package com.wenteryan.watermarkspringmvc;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wenteryan.service.MarkService;
import com.wenteryan.service.UploadService;

@Controller
public class WatermarkAction {

 private MarkService mackService ;
 private UploadService uploadService ;

 @RequestMapping(value="/watermark", method=RequestMethod.POST)
 public ModelAndView watermark(
   @RequestParam("image")CommonsMultipartFile file, HttpSession session) throws Exception {
  String uploadPath = "/images" ;
  String realUploadPath = session.getServletContext().getRealPath(uploadPath) ;
  String imageUrl = uploadService.uploadImage(file, uploadPath, realUploadPath) ;
  String logoImageUrl = mackService.watermark(file, uploadPath, realUploadPath) ;
  ModelAndView ret = new ModelAndView() ;
  ret.addObject("imageUrl", imageUrl) ;
  ret.addObject("logoImageUrl", logoImageUrl) ;
  ret.setViewName("watermark");

  return ret ;
 }

 @Autowired
 public void setMackService(MarkService mackService) {
  this.mackService = mackService;
 }
 @Autowired
 public void setUploadService(UploadService uploadService) {
  this.uploadService = uploadService;
 }


}

4.编写服务类

MarkService .java

package com.wenteryan.service;
import java.awt.Color;
import java.awt.Font;
import java.io.File;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

public interface MarkService {

 public static final String MARK_TEXT = "wenteryan" ;
 public static final String FONT_NAME = "微软雅黑" ;

 public static final int FONT_SIZE = 120 ;
 public static final int FONT_STYPE = Font.BOLD ;
 public static final Color FONT_COLOR = Color.RED ;

 public static final int X = 10 ;
 public static final int Y = 10 ;

 public static float ALPHA = 0.3F ;

 public String watermark(CommonsMultipartFile file, String uploadPath, 
   String realUploadPath) ; 

}

5.编写接口实现类

UploadService .java

package com.wenteryan.service.impl;

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

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Service
public class UploadService {

 public String uploadImage(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
  InputStream is = null ;
  OutputStream os = null ;

  try {

   is = file.getInputStream() ;
   os = new FileOutputStream(realUploadPath+"/"+file.getOriginalFilename()) ;

   byte[] buffer = new byte[1024] ;
   int len = 0 ;

   while((len=is.read(buffer))>0) {
    os.write(buffer) ;
   }

  } catch(Exception e) {
   e.printStackTrace() ;
  } finally {
   if(is!=null) {
    try {
     is.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if(os!=null) {
    try {
     os.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

  return uploadPath+"/"+file.getOriginalFilename() ;
 }
}



MarkServiceImpl .java

package com.wenteryan.service.impl;

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

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.wenteryan.service.MarkService;

@Service
public class MarkServiceImpl implements MarkService {

 @Override
 public String watermark(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
  // TODO Auto-generated method stub

  String logoFileName = "logo"+file.getOriginalFilename() ;
  OutputStream os = null ;
  try {
   Image image2 = ImageIO.read(file.getInputStream()) ;

   int width = image2.getWidth(null) ;
   int height = image2.getHeight(null) ;

   BufferedImage bufferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) ;

   Graphics2D g = bufferImage.createGraphics() ;
   g.drawImage(image2, 0, 0, width, height, null) ;

   g.setFont(new Font(FONT_NAME,FONT_STYPE,FONT_SIZE));
   g.setColor(FONT_COLOR) ;

   int width1 = FONT_SIZE*getTextLength(MARK_TEXT) ;
   int height1 = FONT_SIZE ;

   int widthDiff = width-width1 ;
   int heightDiff = height-height1 ;

   int x = X ;
   int y = Y ;

   if(x>widthDiff) {
    x = widthDiff ;
   }

   if(y>heightDiff) {
    y=heightDiff ;
   }

   g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));

   g.drawString(MARK_TEXT, x, y+FONT_SIZE) ;
   g.dispose() ;

   os = new FileOutputStream(realUploadPath+"/"+logoFileName) ;
   JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os) ;
   en.encode(bufferImage) ;

  } catch(Exception e) {
   e.printStackTrace() ;
  } finally {
   if(os!=null) {
    try {
     os.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }

  return uploadPath+"/"+logoFileName;
 }

 public 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 ;
 }

}

6.编写页面
index.jsp

<form action="watermark" method="post" enctype="multipart/form-data">
  <h2>请选择上传的图片</h2>
  <div class="form-group">
  <br>
  <input type="file" name="image" id="image" />
  </div>
  <div class="form-group">
  <br>
  <button class="btn btn-success" type="submit">开始上传</button>
  </div>
 </form>

watermark.jsp

<div class="panel-body">
  <img class="img-responsive img-rounded" src="${pageContext.request.contextPath}${imageUrl }"/>

  <img class="img-responsive img-rounded" src="${pageContext.request.contextPath}${logoImageUrl }"/>
  <a class="btn btn-warning" href="${pageContext.request.contextPath }">返回</a>

 </div>

总结

Java有专门Image的处理包,同样应该可以实现水印功能,查了资料小试下来发现java实现水印还是非常方便的,水印可以是图片或者文字,后期会有水印图片水印,以后有需要可以写个代码批量处理自己的图片了。

以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。

相关文章

  • 关于SpringBoot禁止循环依赖解说

    关于SpringBoot禁止循环依赖解说

    这篇文章主要介绍了关于SpringBoot禁止循环依赖解说,Spring的Bean管理,文章围绕主题展开详细介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-05-05
  • Mapstruct @Mapper @Mapping 使用小结

    Mapstruct @Mapper @Mapping 使用小结

    这篇文章主要介绍了Mapstruct @Mapper @Mapping使用小结,他们用于各个对象实体间的相互转换,例如数据库底层实体转为页面对象,Model 转为 DTO, DTO 转为其他中间对象, VO 等等,相关转换代码为编译时自动产生的新文件和代码,需要的朋友可以参考下
    2023-09-09
  • 详解Spring Boot中PATCH上传文件的问题

    详解Spring Boot中PATCH上传文件的问题

    这篇文章主要介绍了详解Spring Boot中PATCH上传文件的问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • 详细聊一聊java语言中的package和import机制

    详细聊一聊java语言中的package和import机制

    这篇文章主要给大家介绍了关于java语言中package和import机制的相关资料,Java中的package是指将相关的类组织在一起的一种机制,它可以用来避免命名冲突,也可以方便地管理和维护代码,需要的朋友可以参考下
    2024-01-01
  • 新手小白入门必学JAVA面向对象之多态

    新手小白入门必学JAVA面向对象之多态

    说到多态,一定离不开其它两大特性:封装和继承,下面这篇文章主要给大家介绍了关于新手小白入门必学JAVA面向对象之多态的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-02-02
  • Java NIO 中 Selector 解析

    Java NIO 中 Selector 解析

    这篇文章主要介绍了Java NIO 中 Selector,Selector即选择器,选择器提供选择执行已经就绪的任务的能力即为翻译为多路复用,下面文章对Selector详细介绍内容,需要的小伙伴可以参考一下
    2022-02-02
  • application.yml和bootstrap.yml不生效的3种解决方案

    application.yml和bootstrap.yml不生效的3种解决方案

    SpringBoot默认支持 properties(.properties) 和 YAML(.yml .yaml ) 配置文件,本文主要介绍了application.yml和bootstrap.yml不生效的3种解决方案,具有一定的参考价值,感兴趣的可以了解一下
    2024-03-03
  • Java运算符从见过到掌握下

    Java运算符从见过到掌握下

    计算机的最基本用途之一就是执行数学运算,作为一门计算机语言,Java也提供了一套丰富的运算符来操纵变量,本篇对大家的学习或工作具有一定的价值,紧接上篇,需要的朋友可以参考下
    2021-09-09
  • 完整详解Java开发学习路线指南

    完整详解Java开发学习路线指南

    在本篇文章里小编给大家整理的是一篇关于Java开发学习路线以及期中的主要知识点内容,有兴趣的朋友么可以学习下。
    2022-11-11
  • SpringBoot中使用@Scheduled注解创建定时任务的实现

    SpringBoot中使用@Scheduled注解创建定时任务的实现

    这篇文章主要介绍了SpringBoot中使用@Scheduled注解创建定时任务的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06

最新评论