Web應用為上傳圖檔生成縮略圖是常見的基本功能,通過縮略圖生成提高了資訊浏覽時的性能,在保證使用者使用體驗的同時減少了資料傳輸量。本次以執行個體的方式,講解如何使用使用Java實作圖檔等比例縮略圖生成功能。
效果檢視
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiM0ATNxQTN1EDOwUDM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
代碼編寫
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 = ;
public static final int HEIGHT = ;
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[] ;
int len = ;
while((len=is.read(buffer))>) {
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、提高程式性能和效率。