Spring boot MultipartFile 头像图片同比例缩小转码BASE64 转Image 笔记

@ResponseBody
		@RequestMapping({ "/image/{key}"})
	    public OutputObject importImage(@PathVariable String key,
										@RequestParam MultipartFile file
										,@RequestParam Map params,
										HttpSession httpSession, HttpServletRequest request,HttpServletResponse response) throws IOException {

			OutputObject outputObject = new OutputObject();
			String base64EncoderImg = null;
			Image image = ImageIO.read(file.getInputStream());
			int  widthAndHeight=60;
			BufferedImage bufferedimage = new BufferedImage(widthAndHeight, widthAndHeight, BufferedImage.TYPE_INT_RGB);
			bufferedimage.getGraphics().drawImage(image, 0, 0, widthAndHeight, widthAndHeight, null); // 绘制缩小后的图
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

			String originalFilename = file.getOriginalFilename();
			String fileType = originalFilename.substring(originalFilename.indexOf(".") + 1);

			ImageIO.write(bufferedimage, fileType, outputStream);
			BASE64Encoder encoder = new BASE64Encoder();
			if (fileType.equals("png") || fileType.equals("jpg") || fileType.equals("jpeg")) {
				String base64Img = encoder.encode(outputStream.toByteArray());
				base64EncoderImg = "data:image/" + (fileType.equals("png") ? "png" : "jpeg") + ";base64," + base64Img;
				outputObject.setUrl(base64EncoderImg.replaceAll("\r|\n", ""));
				outputObject.setMsg("上传图片成功");
				outputObject.setCode("1");

			} else {
				outputObject.setMsg("上传图片失败:类型错误");
				outputObject.setCode("0");
			}
			return outputObject;
		}

可能有没用的代码,直接copy放这里了,就这吧

你可能感兴趣的:(代码笔记)