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

@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放这里了,就这吧

在Java中,Base64编码通常用于将二进制数据(如图像、文件内容)换为可文本表示的形式。当你想要从Base64字符串换回`MultipartFile`,这是因为`MultipartFile`是Spring MVC中用于处理上传文件的模型属性,而Base64的解码可以让你把字符串还原成原始二进制文件。 首先,你需要一个Base64编码的字符串,然后将其解码成字节数组。接着,你可以创建一个新的`InputStream`或`ByteArrayInputStream`,并将这个字节数组传递给`MultipartFile`构造函数,或者使用`FileUtils.readFileToByteArray()`等方法读取为字节流。 以下是一个简单的示例代码片段: ```java import org.springframework.web.multipart.MultipartFile; import java.util.Base64; import java.io.ByteArrayInputStream; import org.springframework.util.FileCopyUtils; public MultipartFile base64ToMultipartFile(String base64EncodedData) { byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedData); ByteArrayInputStream bais = new ByteArrayInputStream(decodedBytes); try { // 使用FileCopyUtils确保字节流被正确关闭 return new MultipartFile("file", "originalFilename", "application/octet-stream", bais, decodedBytes.length); } catch (Exception e) { throw new RuntimeException("Failed to convert Base64 to MultipartFile", e); } } // 如果你有完整的Base64字符串,可以这样使用: String base64String = "your_base64_string_here"; MultipartFile file = base64ToMultipartFile(base64String); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值