1. 程式人生 > >Java 實現圖片等比例縮圖 (Thumbnailator + Jsp+SpringMVC)

Java 實現圖片等比例縮圖 (Thumbnailator + Jsp+SpringMVC)

Web應用為上傳圖片生成縮圖是常見的基本功能,通過縮圖生成提高了資訊瀏覽時的效能,在保證使用者使用體驗的同時減少了資料傳輸量。本次以例項的方式,講解如何使用使用Java實現圖片等比例縮圖生成功能。

效果檢視

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

程式碼編寫

Thumbnailator 是一個為Java介面更流暢的縮圖生成庫。從API提供現有的影象檔案和影象物件的縮圖中簡化了縮略過程,兩三行程式碼就能夠從現有圖片生成縮圖,且允許微調縮圖生成,同時保持了需要寫入到最低限度的程式碼量。

1.匯入相關的包

這裡寫圖片描述

2.配置web.xml

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>thumbnail</display-name> <!-- 配置 SpringMVC 的 DispatcherServlet -->
<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>

3.配置 springmvc.xml

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>

    <!-- 配置檢視解析器: 如何把 handler 方法返回值解析為實際的物理檢視 -->
    <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>

4.編寫Action

ThumbnailAction.java

@Controller
public class ThumbnailAction {

    public UploadService uploadService ;
    public ThumbnailService thumbnailService ;

    @RequestMapping(value="/thumbnail", method=RequestMethod.POST)
    public ModelAndView thumbnail(@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 thumbImageUrl = thumbnailService.thumbnail(file, uploadPath, realUploadPath) ;
        ModelAndView ret = new ModelAndView() ;
        ret.addObject("imagesUrl", imageUrl) ;
        ret.addObject("thumbnailUrl", thumbImageUrl) ;
        ret.setViewName("thumbnail");   
        return ret ;
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }
    @Autowired
    public void setThumbnailService(ThumbnailService thumbnailService) {
        this.thumbnailService = thumbnailService;
    }
}

5.編寫service

ThumbnailService .java

@Service
public class ThumbnailService {

    public static final int WIDTH = 100 ;
    public static final int HEIGHT = 100 ;

    public String thumbnail(CommonsMultipartFile file, String uploadPath, String realUploadPath) {

        try {
            String des = realUploadPath +"/thum_" + file.getOriginalFilename() ;
        Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des); ;
        } catch(Exception e) {
            e.printStackTrace() ;
        } 
        return uploadPath + "/thum_" + file.getOriginalFilename() ;
    }
}

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() ;
            String des = realUploadPath + "\\" + file.getOriginalFilename() ;
            os = new FileOutputStream(des) ;
            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() ;
    }
}

6.編寫 jsp 檔案

index.jsp

<div class="panel panel-warning">
    <div class="panel-heading"><h2>Java 實現圖片等比例縮圖</h2></div>
    <div class="panel-body">
    <form action="thumbnail" method="post" enctype="multipart/form-data">
        <h2>請選擇上傳的圖片</h2>
        <div class="form-group">
        <input type="file" name="image" id="image" />
        </div>
        <div class="form-group">
        <button class="btn btn-success" type="submit">開始上傳</button>
        </div>
    </form>
    </div>
</div>

thumbnail.jsp

<div class="panel panel-warning">
    <div class="panel-heading"><h2>原圖片與縮圖</h2></div>
    <div class="panel-body">
        <img alt="" src="${pageContext.request.contextPath }${imagesUrl }"/>
        <img alt="" src="${pageContext.request.contextPath }${thumbnailUrl }"/>
        <br><br>
        <a class="btn btn-warning" href="${pageContext.request.contextPath }">返回</a>
    </div>
</div>

技術總結

實現圖片縮圖的好處總結如下:

1、節省儲存空間。
2、更加靈活響應運營部的多尺寸圖片需求。
3、提高程式效能和效率。