1.簡介:Web應用為上傳圖片生成縮略圖是常見的基本功能,通過縮略圖生成提高了信息瀏覽時的性能,在保證用戶使用體驗的同時減少了數據傳輸量。
2.實現圖片等比例縮略圖生成,方式及相關工具介紹:
(1)Thumbnailator類庫(推薦)
工具:size()API方法
(2)Java AWT類庫(復雜)
根據縮略比例計算縮略圖高度賀寬度,使用Image類獲得原圖的縮放版本,使用ImageIO類保存縮略圖;
工具:bufferedImage(圖像的存儲和操作);ImageIO(圖片讀入、輸出、生成);Graphics(圖片的繪制)。
本實例是基於springMVC框架的Java web應用程序,允許上傳圖片,並生成圖片的縮略圖。
3.實現步驟
(1)應用程序框架搭建;
(2)上傳文件界面的開發;
(3)控制器開發;
(4)編寫圖片上傳服務類;
(5)編寫縮略圖生成服務類
需要的關鍵壓縮使用的jar包:
搭建web項目目錄:
直接上核心代碼:
控制層controller實現:
@Controller @RequestMapping("/") public class ThumbnailController { @Autowired private UploadService uploadService; @Autowired private ThumbnailService thumbnailService; @RequestMapping(value="/thumbnail",method=RequestMethod.POST) public ModelAndView thumbnail(@RequestParam("image") CommonsMultipartFile file,HttpSession session) throws Exception{ System.out.println("========================="); //主要針對於圖片上傳 //相對路徑 String uploadPath="/images"; //圖片在服務器上的絕對路徑信息 String realUploadPath=session.getServletContext().getRealPath(uploadPath); //返回的結果 //圖片原圖在服務器上訪問的相對路徑信息 String imageUrl=uploadService.uploadImage(file, uploadPath, realUploadPath); //縮略圖訪問路徑 String thumImageUrl=thumbnailService.thumbnail(file, uploadPath, realUploadPath); //設置返回前端顯示(渲染) ModelAndView modelAndView=new ModelAndView(); modelAndView.addObject("imageURL", imageUrl); modelAndView.addObject("thumImageURL", thumImageUrl); modelAndView.setViewName("thumbnail"); return modelAndView; } }
文件上傳的業務實現類,代碼(service):
/** * 文件上傳文件的處理 */ @Service public class UploadService { public String uploadImage(CommonsMultipartFile file,String uploadPath,String realUploadPath){ InputStream iStream=null; OutputStream oStream=null; try { //獲取上傳文件的流文件 iStream=file.getInputStream(); //創建文件輸出流與位置 String des=realUploadPath+"/"+file.getOriginalFilename(); oStream=new FileOutputStream(des); byte[] buffer=new byte[1024]; while (iStream.read(buffer)>0) { oStream.write(buffer); } } catch (Exception e) { e.printStackTrace(); }finally { if(iStream!=null){ try { iStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(oStream!=null){ try { oStream.close(); } catch (IOException e) { e.printStackTrace(); } } } //返回文件上傳的相對路徑 return uploadPath+"/"+file.getOriginalFilename(); } }
圖片縮略處理,實現方式:
(1)Thumbnails圖片縮略處理,代碼如下:
/** * Thumbnails圖片縮略處理 */ @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(); //圖片縮略圖實現,強制按照指定的寬高進行縮略keepAspectRatio(false)
//方式一 // Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des); //方式二
Builder<? extends InputStream> thumbnail = Thumbnails.of(file.getInputStream()); thumbnail.size(WIDTH, HEIGHT); thumbnail.toFile(des); } catch (Exception e) { e.printStackTrace(); } //縮略圖返回的相對路徑 return uploadPath+"/thum_"+file.getOriginalFilename(); } }
(2)AWT圖片縮略處理,代碼如下:
/** * AWT圖片縮略處理 */ @Service public class AWTService { public static final int WIDTH=100; public static final int HEIGHT=100; public String thumbnail(CommonsMultipartFile file,String uploadPath,String realUploadPath){ OutputStream oStream=null; try { String des=realUploadPath+"/thum_"+file.getOriginalFilename(); oStream=new FileOutputStream(des); //ImageIO獲取圖片流信息 Image image=ImageIO.read(file.getInputStream()); int width=image.getWidth(null); //獲取原圖寬度 int height=image.getHeight(null);//獲取原圖高度 int wrate=width/WIDTH; //寬度縮略圖 int hrate=height/HEIGHT;//高度縮略圖 int rate=0; if (wrate>hrate) {//寬度縮略圖比例大於高度縮略圖,使用寬度縮略圖 rate=wrate; } else { rate=hrate; } //計算縮略圖最終的寬度和高度 int newWidth=width/rate; int newHeight=height/rate; BufferedImage bufferedImage=new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); //圖片縮略圖實現 bufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, image.SCALE_SMOOTH), 0, 0, null); //*image/jpeg String imageType=file.getContentType().substring(file.getContentType().indexOf("/")+1); ImageIO.write(bufferedImage, imageType, oStream); } catch (Exception e) { e.printStackTrace(); }finally { try { oStream.close(); } catch (IOException e) { e.printStackTrace(); } } //縮略圖返回的相對路徑 return uploadPath+"/thum_"+file.getOriginalFilename(); } }
配置信息一,web容器配置,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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0"> <display-name>ImageCompress</display-name> <!-- 設置前端攔截器,springmvc容器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- springmvc具體配置信息 --> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 狀態1表示,web應用是隨web容器啟動而啟動 --> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!-- 表示攔截所有的url路徑 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
配置信息二,springmvc容器配置,spring-mvc.xml:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 開啟注解 --> <mvc:annotation-driven/> <!-- 注意:在spring的配置文件中,配置包掃描器時,只使用了*,想掃描所有的包,這種會造成錯誤;而這種方式有可能掃描到spring自帶的包, 造成錯誤 --> <!-- *表示掃描所有子包下面的注解文件 --> <!-- <context:component-scan base-package="com.*"/> --> <!-- 表示掃描所有包下面所有java文件的注解文件 --> <context:component-scan base-package="com.thumbnail"/> <!-- 文件上傳 --> <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> <!-- 當在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射時,能映射靜態資源 --> <mvc:default-servlet-handler /> <!-- 默認的視圖解析器 在上邊的解析錯誤時使用 (默認使用html)- --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="contentType" value="text/html" /> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> </beans>