Java 实现图片水印之文字水印(SpringMVC + Jsp)

看之前要先对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实现水印还是非常方便的,水印可以是图片或者文字,后期会有水印图片水印,以后有需要可以写个代码批量处理自己的图片了。

时间: 2024-10-10 08:43:54

Java 实现图片水印之文字水印(SpringMVC + Jsp)的相关文章

图片工具类, 图片水印,文字水印,缩放,补白等

import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import

.NET图片操作类,包含图片格式转换、图片缩放、 文字水印、图片水印、路径转换

using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Drawing.Imaging;using System.Drawing;using System.Web;namespace ZC.Utils{  public  static class ImageHelper  { #region 图片格式转换      /// <summary>      /// 图片

java创建透明背景的PNG图片加自定义文字水印

人在码上走,奇葩需求天天有.这不,今天前端让我返回一个带自定义水印的背景图片.一通google,有现成的代码,但是很多是直接在源图上添加水印,生成出来的文字样式也没有控制好,看来又只有自己造轮子了. 过程有点曲折,直接上最终代码: import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.RenderingHint

Thinkphp图片水印和文字水印

1.Thinkphp图像处理 在TP框架中,我们经常用到图片上传,我最近写了很多关于图片上传的文章,thinkphp图片上传+validate表单验证+图片木马检测+缩略图生成等文章,今天写一下关于图片上传成功后给图片加水印文字或者加图片水印, 1.1图片处理类和库 首先,在Thinkphp\Think\Image类中有图像处理功能,支持Gd库和Imagick库,包括对GIf图像处理的支持. 1.2实例化类库 $image = new \Think\Image(); 实例化image后,默认使用

在图片上添加文字水印

1 <?php 2 /** 3 打开任何一种格式的图片 在图片的中间加上一个文字水印 保存 4 只是保存下来 并不会输出到浏览器 5 */ 6 function imagewater($filename,$string){ 7 //获得图片的属性 8 list($width,$height,$type) = getimagesize($filename); 9 //可以处理的照片的类型 10 $types = array(1=>"gif",2=>"jpeg&

利用iTextSharp组件给PDF文档添加图片水印,文字水印

最近在做关于PDF文档添加水印的功能,折腾了好久,终于好了.以下做个记录: 首先会用到iTextSharp组件,大家可以去官网下载,同时我也会在本文中附加进来. 代码中添加引用为:   using System; using System.Collections.Generic; using System.Linq; using System.Text; using iTextSharp.text.pdf; using System.IO; using iTextSharp.text; 创建一个

Java 实现图片等比例缩略图 (Thumbnailator + Jsp+SpringMVC)

Web应用为上传图片生成缩略图是常见的基本功能,通过缩略图生成提高了信息浏览时的性能,在保证用户使用体验的同时减少了数据传输量.本次以实例的方式,讲解如何使用使用Java实现图片等比例缩略图生成功能. 效果查看 代码编写 Thumbnailator 是一个为Java界面更流畅的缩略图生成库.从API提供现有的图像文件和图像对象的缩略图中简化了缩略过程,两三行代码就能够从现有图片生成缩略图,且允许微调缩略图生成,同时保持了需要写入到最低限度的代码量. 1.导入相关的包 2.配置web.xml we

php生成文字水印和图片水印

生成文字水印 <?php //文字水印 /*打开图片*/ //1.配置图片路径 $src = "4.jpg"; //2.获取图片的信息(得到图片的基本信息) $info = getimagesize($src ); //3.通过获取图片类型 $type = image_type_to_extension($info[2],false); //4.在内存中创建一个图片类型一样的图像 $fun = "imagecreatefrom{$type}"; //5.图片复

安全权限、高性能、高并发、分布式java shiro、maven、Bootstrap、SpringMVC、Mybatis

获取[下载地址]   QQ: 313596790   [免费支持更新]支持三大数据库 mysql  oracle  sqlsever   更专业.更强悍.适合不同用户群体[新录针对本系统的视频教程,手把手教开发一个模块,快速掌握本系统]A 代码生成器(开发利器);      增删改查的处理类,service层,mybatis的xml,SQL( mysql   和oracle)脚本,   jsp页面 都生成   就不用写搬砖的代码了,生成的放到项目里,可以直接运行B 阿里巴巴数据库连接池druid