上传图片保存并生成缩略图

java工具thumbnailator

jar下载地址:httpmvnrepository.comartifactnet.coobirdthumbnailator


过程讲解:一个springMvc的上传文件框架

1.上传文件,后台接受文件对象

2.正常将文件上传保存到服务器

3.将图片文件通过工具生成缩略图

html的代码:

选择文件

controller代码:

@Controller
@RequestMapping("image")
public class ImageController {
	
	@RequestMapping("upload")
	private String upload(HttpServletRequest request ,@RequestParam("file") CommonsMultipartFile file) throws Exception{
		String uploadPath = "/image";	//相对路径
		System.out.println("uploadPath="+uploadPath);	//相对路径对应的真是路径
		String realUploadPath = request.getSession().getServletContext().getRealPath(uploadPath);
		System.out.println("realUploadPath="+realUploadPath);
		
		String imgUrl= "";
		String thumImgUrl= "";
		
		imgUrl = UploadImageUtil.uploadImage(file, uploadPath, realUploadPath);
		thumImgUrl = UploadImageUtil.thumbnailUploadImage(file, 100, 100, uploadPath, realUploadPath);
		request.setAttribute("imgUrl",imgUrl);
		request.setAttribute("thumImgUrl",thumImgUrl);
		return "showImage";
	}
}

UploadImageUtil代码:

import net.coobird.thumbnailator.Thumbnails;
public class UploadImageUtil {
	
	/**
	 * 上传文件
	 * @param file	上传的文件
	 * @param uploadPath	上传路径相对路径
	 * @param realUploadPath	原图实际路径
	 * @return
	 */
	public static 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, 0, len);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return uploadPath + "/"+file.getOriginalFilename();
	}
	//生成缩略图
	public static String thumbnailUploadImage(CommonsMultipartFile file,int width,int height,String uploadPath,String realUploadPath){
		String des = realUploadPath + "/thum"+file.getOriginalFilename();//缩略图实际存储路径
		try {
			Thumbnails.of(file.getInputStream()).size(width, height).toFile(des);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return uploadPath + "/thum"+file.getOriginalFilename();
	}
}
结束

你可能感兴趣的:(之前博文,图片,thumbnailator,缩略图)