Java实现图片等比例缩略图

二次信任 提交于 2019-12-07 20:52:11

缩略图实现方式及相关工具简介:

方式一:使用Thumbnailator类库,size()API方法

方式二:Java AWT类库。根据缩略比例计算缩略图高度和宽度,使用Image类获得原图的缩放版本,最后使用ImageIO类获得原图的缩放版本。BufferedImage、Image、ImageIO

环境搭建:


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"
	id="WebApp_ID" version="3.0">
	<display-name>thumbnail</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: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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<mvc:default-servlet-handler/>
	
	<mvc:annotation-driven/>
	
	<!-- 默认扫描所有包下的java文件 -->
	<context:component-scan base-package="*"/>
	
	<!-- 默认的视图解析器,它会分析控制器返回的视图名称,并且按照我们指定的路径、后缀名做处理,最后将操作结果做个渲染和展示-->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<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>

编写控制器:

ThumbnailAction.java

package com.thumbnail;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/")
public class ThumbnailAction {

	public ModelAndView thumbnail(@RequestParam("image")CommonsMultipartFile file,HttpSession session) throws Exception{
		String uploadPath = "/images";//上传路径,也就是相对路径
		String realUploadPath = session.getServletContext().getRealPath(uploadPath);//真实的路径,也就是绝对路径
		
		String imageUrl = "";//原图片路径
		String thumImageUrl = "";//缩略图路径
		
		ModelAndView ret = new ModelAndView();
		ret.addObject("imageURL", imageUrl);
		ret.addObject("thumbImageURL", thumImageUrl);
		ret.setViewName("thumbnail");
		return ret;
	}
}

上传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=UTF-8">
<title>上传文件</title>
</head>
<body>
	<form id="upload_form" enctype="multipart/form-data" method="post" 
		  action="${pageContext.request.contextPath}/thumbnail">
		<h2>请选择上传图片</h2>
		<div>
			<input type="file" name="image" id="image"/>
			<input type="submit" value="上传">
		</div>
	</form>
</body>
</html>

图片上传服务类开发

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;

@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);//获取输出流,用于将文件写入服务器响应的路径下,这里是 /images
			
			byte[] buffer = new byte[1024];
			int len = 0;
			
			while((len=is.read(buffer))>0){
				os.write(buffer);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					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;

@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();
			/**
			 * Thumbnailator 是一个用来生成图像缩略图的 Java 类库,通过很简单的代码即可生成图片缩略图
			 */
			Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(des);
		}catch(Exception e){
			e.printStackTrace();
		}
		return uploadPath + "/thum_"+file.getOriginalFilename();
	}
}

AWT版本服务类讲解

ThumbnailAWTService.java
package com.thumbnail;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Service
public class ThumbnailAWTService {
	public static final int WIDTH=100;
	public static final int HEIGHT=100;
	
	public String thumbnail(CommonsMultipartFile file,String uploadPath,String realUploadPath){
		OutputStream os = null;
		try{
			String des  = realUploadPath + "/thum_" + file.getOriginalFilename();
			os = new FileOutputStream(des);
			Image image = ImageIO.read(file.getInputStream());
			int width = image.getWidth(null);//原图宽度
			int height = image.getHeight(null);//原图高度
			
			int rate1 = width / WIDTH;//宽度缩略比例
			int rate2 = height /HEIGHT;//高度缩略比例
			
			int rate = 0;
			if(rate1 > rate2){//宽度缩略比例大于高度缩略比例,使用宽度缩略比例
				rate = rate1;
			}else{
				rate = rate2;
			}
			
			
			//计算缩略图最终的宽度和高度
			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, os);
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return uploadPath + "/" + file.getOriginalFilename();
	}
}

控制器完善&展示页面编写

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.servlet.ModelAndView;
@Controller
@RequestMapping("/")
public class ThumbnailAction {
	
	private UploadService uploadService;
	private 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 thumImageUrl = thumbnailService.thumbnail(file, uploadPath, realUploadPath);//缩略图路径
				
		ModelAndView ret = new ModelAndView();
		ret.addObject("imageURL", imageUrl);
		ret.addObject("thumbImageURL", thumImageUrl);
		ret.setViewName("thumbnail");
		return ret;
	}
	@Autowired
	public void setUploadService(UploadService uploadService) {
		this.uploadService = uploadService;
	}
	@Autowired
	public void setThumbnailService(ThumbnailService thumbnailService) {
		this.thumbnailService = thumbnailService;
	}
	
}
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=utf-8">
<title>操作结果</title>
</head>
<body>
	<h4>图片信息</h4>
	<hr/>
	<table width="100%">
		<tr width="50%" align="center">
			<img src="${pageContext.request.contextPath}${imageURL}" width="500"/>
		</tr>
		<tr width="50%" align="center">
			<img src="${pageContext.request.contextPath}${thumbImageURL}"/>
		</tr>
	</table>
	<hr/>
	<a href="${pageContext.request.contextPath}">返回</a>
	<hr/>
</body>
</html>
源码下载:http://download.csdn.net/detail/btt2013/9667998





标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!