java實現等比例縮略圖

方式一、Thumbnailator類庫:size()API方法,

方式二、Java AWT類圖實現:根據縮略比例計算縮略圖高度和寬度,使用Image類獲得原圖的縮放版本,使用ImageIO類保存縮略圖---BufferedImage,ImageIO,Graphips

案例:

springMVC搭建:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Thumbrail</display-name>
  <servlet>
  	<servlet-name>springmvc</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:applicationContext-mvc.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
applicationContext-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	">
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven/>
	<context:component-scan base-package="*"/>
	<bean id="biewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolve">
		<property name="prefix" value="/"/>
		<property name="suffix" value=".jsp"/>
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
	</bean>
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8"/>
		<property name="maxUploadSize" value="10485760000"/>
		<property name="maxInMemorySize" value="40960"/>
	</bean>
	
	  </beans>
index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>上傳文件</title>
</head>
<body>
<div class="demo">
	<div class="bheader">
		<h2>---圖片文件上傳---</h2>
	</div>
	<div class="bbody">
		<form id="upload_form" enctype="multipart/from-data" method="post" action="${pageContext.request.contextPath}/thumbnail" >
			<h2>請選擇上傳圖片</h2>
			<div>
				<input type="file" name="image" id="image"/>
				<input type="submit" value="上傳"/>
			</div>
		</form>
	</div>
</div>
</body>
</html>
thumbnailAction.java

package com.thumbnail;

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.portlet.ModelAndView;

@Controller
@RequestMapping("/")
public class ThumbnailAction {
	private UploadService u ;
	private ThumbnailService t;
	//springmvc會將用戶提交的文件信息封裝成爲CommonsMultipartFile文件類型:方法的參數名稱file和文件中提交的文件名稱image是不對應的,需要註解下,讓其統一
	@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 imagerUrl = u.uploadImage(file, uploadPath, realUploadPath);;//原圖路徑
		String thumImageUrl = t.thumbnail(file, uploadPath, realUploadPath);//縮略圖路徑
		
		ModelAndView ret = new ModelAndView();
		ret.addObject("imageURL",imagerUrl);
		ret.addObject("thumImageURL",thumImageUrl);
		
		ret.setViewName("thumbnail");
		return ret;
	}
	@Autowired
	public void setU(UploadService u) {
		this.u = u;
	}
	@Autowired
	public void setT(ThumbnailService t) {
		this.t = t;
	}
}
uploadService.java

package com.thumbnail;

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;
/**
 * 文件上傳實現
 * @author Administrator
 *
 */
@Service
public class UploadService {
	
	public String uploadImage(CommonsMultipartFile file,String uploadPath,String realUploadPath){
		InputStream is = null;
		OutputStream out = null;
		try {
			is = file.getInputStream();//得到文件流
			String des = realUploadPath + "/" +file.getOriginalFilename();
			out = new FileOutputStream(des);//得到輸出流
			
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = is.read(buffer)) > 0){
				out.write(buffer);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return uploadPath+"/"+file.getOriginalFilename();
	}
}
ThumbnailService.java

package com.thumbnail;

import net.coobird.thumbnailator.Thumbnails;

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

/**
 * 縮略圖服務類
 * @author Administrator
 *
 */
@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) {
			// TODO: handle exception
		}
		
		return uploadPath + "/thum_" + file.getOriginalFilename();
	}
}
thumbnail.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>操作結果</title>
</head>
<body>
<h4>圖片信息</h4>
<hr />
<table width="200">
	<tr>
		<td width="50%" align="center"><img src="${pageContext.request.contextPath }${imageURL}" width="500"></td>
		<td width="50%" align="center"><img src="${pageContext.request.contextPath }${thumbImageURL}" /></td>
	</tr>
</table>
<hr/>
<a href="${pageContext.request.contextPath }">返回</a>
</body>
</html>








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章