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

图片水印不仅水印文字还可以是图片,本次实现图片水印之水印图片,以后有需要可以用个代码批量处理自己的图片了。

大家先看效果图

代码编写

1.导入相关架包

2.配置XML文件

web.xml

    <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>

springmvc.xml

    <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>

3.编写服务类接口

ImageMarkService.java

public static final String LOGO = "logo.png" ;

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

4.编写服务类实现

UploadService.java

@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() ;
    }
}

ImageMarkServiceImpl.java

@Service
public class ImageMarkServiceImpl implements ImageMarkService {

    @Override
    public String watermark(CommonsMultipartFile file, String uploadPath, String realUploadPath) {
        // TODO Auto-generated method stub
        String logoFileName = "logoImage"+file.getOriginalFilename() ;
        OutputStream os = null ;

        String logoPath = realUploadPath+"/"+LOGO ;
        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) ;

            File logo = new File(logoPath) ;
            Image imageLogo = ImageIO.read(logo) ;

            int width1 = imageLogo.getWidth(null) ;
            int height1 = imageLogo.getHeight(null) ;

            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.drawImage(imageLogo, x, y, null) ;
            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;
    }

}

5.编写Action

WaterMarkAction.java

@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 = imageMarkService.watermark(file, uploadPath, realUploadPath) ;

        ModelAndView ret = new ModelAndView() ;
        ret.addObject("imageUrl", imageUrl) ;
        ret.addObject("logoImageUrl", logoImageUrl) ;

        ret.setViewName("watermark");

        return ret ;
    }

6.编写页面

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实现水印还是非常方便的,会了水印图片与水印文字,以后有需要可以用这个代码批量处理自己的图片了。棒棒的!!!!!!

时间: 2024-10-13 05:00:33

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

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"

Java图片缩略图裁剪水印缩放旋转压缩转格式-Thumbnailator图像处理

前言 java开发中经常遇到对图片的处理,JDK中也提供了对应的工具类,不过处理起来很麻烦,Thumbnailator是一个优秀的图片处理的开源Java类库,处理效果远比Java API的好,从API提供现有的图像文件和图像对象的类中简化了处理过程,两三行代码就能够从现有图片生成处理后的图片,且允许微调图片的生成方式,同时保持了需要写入的最低限度的代码量.还支持对一个目录的所有图片进行批量处理操作,下边就和大家分享一下java中用Thumbnailator做图片各种处理的方法(相关jar包可在最

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

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

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

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

图片自动加水印

1 package cn.tfri.filter.watermark; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletReque

android图像处理系列之七--图片涂鸦,水印-图片叠加

图片涂鸦和水印其实是一个功能,实现的方式是一样的,就是一张大图片和一张小点图片叠加即可.前面在android图像处理系列之六--给图片添加边框(下)-图片叠加中也讲到了图片叠加,里面实现的原理是直接操作像素点.下面给出别外一种方式让图片叠加--用Canvas处理图片,canvas已经封装好了,直接调用就行. 下面看效果: += 代码: [java] view plain copy /** * 组合涂鸦图片和源图片 * @param src 源图片 * @param watermark 涂鸦图片

php 图片加水印文字水印

/*给图片加文字水印的方法*/ $dst_path = 'http://f4.topitme.com/4/15/11/1166351597fe111154l.jpg';//保证路径正确 $dst = imagecreatefromstring(file_get_contents($dst_path)); /*imagecreatefromstring()--从字符串中的图像流新建一个图像,返回一个图像标示符,其表达了从给定字符串得来的图像 图像格式将自动监测,只要php支持jpeg,png,gi

图片水印(微博图片上面的个人签名)

- (void)viewDidLoad { [super viewDidLoad]; // 1.返回水印图片 UIImage *newImage = [UIImage waterImageWithBg:@"scene" logo:@"logo"]; // 2.显示图片 self.iconView.image = newImage; } - (void)testWater { UIImage *bgImage = [UIImage imageNamed:@"

php给图片加文字水印

<? php /*给图片加文字水印的方法*/ $dst_path = 'http://f4.topitme.com/4/15/11/1166351597fe111154l.jpg'; $dst = imagecreatefromstring(file_get_contents($dst_path)); /*imagecreatefromstring()--从字符串中的图像流新建一个图像,返回一个图像标示符.其表达了从给定字符串得来的图像 图像格式将自己主动监測,仅仅要php支持jpeg,png,