当前位置: 移动技术网 > IT编程>开发语言>Java > java实现图片上加文字水印(SpringMVC + Jsp)

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

善恶图文本,情侣口罩,中国象棋开局

看之前要先对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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网