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

本文介绍了一种图片上传的方法,包括读取图片、压缩至固定尺寸、转换为Base64编码,并返回处理结果。适用于处理PNG、JPG和JPEG格式的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@ResponseBody
		@RequestMapping({ "/image/{key}"})
	    public OutputObject importImage(@PathVariable String key,
										@RequestParam MultipartFile file
										,@RequestParam Map<String, Object> 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放这里了,就这吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值