图片上传和缩略图(thumbnails,awt)

  • 之前项目是保存缩略图是用base6直接保存在数据库中,后面我看到了就想进行优化,放到一个ftp服务器中,可是资金不允许,我就只有自己在本地研究了一下。

  • 在本地重新启动个tomcat,在下面新建一个目录,存放图片,将路径存入数据库,访问直接返回路径给前端,前端当静态资源去获取,下面直接贴我的代码:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.FdfsClientConfig;

import ww.shirodemo.entity.ImagesEntity;
import ww.shirodemo.service.ImageService;

@RestController
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
@RequestMapping("/user")
public class UploadController {
	
	@Autowired 
	ImageService imageService;
	
	private static final long UPLOAD_MAX_SIZE = 1 * 1024 * 1024;
	
	public static final int WIDTH = 100;
	public static final int HEIGHT = 100;

	private static final List UPLOAD_CONTENT_TYPES = new ArrayList<>();
	static {
		UPLOAD_CONTENT_TYPES.add("image/jpeg");
		UPLOAD_CONTENT_TYPES.add("image/bmp");
		UPLOAD_CONTENT_TYPES.add("image/png");
		UPLOAD_CONTENT_TYPES.add("image/gif");
	}
	
	@RequestMapping("/upload")
	public Object upload(@RequestParam("fileName") MultipartFile file) {
		
		Map resultMap = new HashMap<>();
		try {
			//判断图片是否为空
			if(file.isEmpty()) {
				resultMap.put("msg", "上传失败,图片为空");
				return resultMap;
			}
			//检查图片大小
			long fileSize = file.getSize();
			if(fileSize >= UPLOAD_MAX_SIZE) {
				resultMap.put("msg", "上传失败,不能超过" + UPLOAD_MAX_SIZE/1024 + "kb");
			}
			//检查文件类型
			String fileType = file.getContentType();
			if(!UPLOAD_CONTENT_TYPES.contains(fileType)) {
				resultMap.put("msg", "上传失败,不允许上传" + fileType + "类型文件");
			} else {
				//获取文件名字
				String fileName = file.getOriginalFilename();
				int beginIndex1 = fileName.lastIndexOf(".");
				String imageName1 = fileName.substring(0, beginIndex1);
				//文件存储路径
//				String filePath = "E:\\files\\upload\\imags";
				String filePath = "D:\\Tomcat\\Tomcat-7.0.96\\webapps\\imgs";
				//缩略图地址
//				String filePath1 = "D:\\Tomcat\\Tomcat-7.0.96\\webapps\\imgs\\sl" + "\\thum_" + fileName;
				//获取图片宽高 进行等比例缩放
				BufferedImage image = ImageIO.read(file.getInputStream());
				int width = image.getWidth() / 2;
				int height = image.getHeight() / 2;
				
				//使用thumbnails存储缩略图
//				Thumbnails.of(file.getInputStream()).size(WIDTH, HEIGHT).toFile(filePath1);
//				Thumbnails.of(file.getInputStream()).size(width, height).toFile(filePath1);
				//缩略图存储地址
				String thumImageUrl = "D:\\Tomcat\\Tomcat-7.0.96\\webapps\\imgs\\sl\\thum_" + fileName;
				
				//使用awt保存缩略图
				FileOutputStream os = new FileOutputStream(thumImageUrl);
				Image image2 = ImageIO.read(file.getInputStream());
				BufferedImage bufferedImage  = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				bufferedImage.getGraphics().drawImage(image2.getScaledInstance(width, height, image2.SCALE_SMOOTH),0,0,null);
				String imageType = file.getContentType().substring(file.getContentType().indexOf("/") + 1);
				ImageIO.write(bufferedImage, imageType, os);
				os.close();
				//不存在则创建文件夹路径
				File url = new File(filePath);
				if(!url.exists()) {	
					url.mkdirs();
				}
				//保存图片
				File dest = new File(url, fileName);
				try {
					file.transferTo(dest);
					resultMap.put("缩略图", thumImageUrl);
					resultMap.put("msg", "图片保存成功");
				} catch (Exception e) {
					e.printStackTrace();
					resultMap.put("msg", "图片保存失败");
				}
				
				//将图片文件存储到数据库 保存为路径+名字+格式
				ImagesEntity findByName = imageService.findByName(imageName1, url.toString());
				if(findByName == null) {
					ImagesEntity iEntity = new ImagesEntity();
					//按照图片完整名称格式之前小数点得到图片名称和图片格式
					String originakFilename = file.getOriginalFilename();
					int beginIndex = originakFilename.lastIndexOf(".");
					//获取图片名名称
					String imageName = originakFilename.substring(0, beginIndex);
					iEntity.setName(imageName);
					iEntity.setUrl(url.toString());
					Date time = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String createTime = sdf.format(time);
					iEntity.setCreate_time(createTime);
					//获取上传图片的格式
					String format = originakFilename.substring(beginIndex);
					iEntity.setFormat(format);
					imageService.insertImage(iEntity);
				} else {
					resultMap.put("msg", "当前路径中已存在该图片");
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("msg", "失败");
		}
		
		return resultMap;
	}
	
}

你可能感兴趣的:(图片上传和缩略图(thumbnails,awt))