部分代码接上文
一、代码
/**
* 后端图片裁剪多余空白区域
* 返回BASE64编码字符串 - 白底黑字(测试)
*
* @param file 上传单个文件
* @return java.lang.String
* @author Tansj
* @since 2021/05/17
*/
@Override
public String trimCutImageFile(MultipartFile file) throws Exception {
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
log.info("原图片宽度:==={},原图片高度:==={}", width, height);
int[] arr = bufferedImageToIntArray(bufferedImage, width, height);
if (arr != null && arr[2] > 0 && arr[3] > 0) {
// blank是作为四周边距留白
int blank = 20;
BufferedImage newBufferedImage = bufferedImage.getSubimage(arr[0] - blank, arr[1] - blank, arr[2] + blank * 2, arr[3] + blank * 2);
ImageIO.write(newBufferedImage, "png", outputStream);
byte[] bytes = outputStream.toByteArray();
// 转BASE64编码字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64String = encoder.encodeBuffer(bytes).trim();
return base64String.replaceAll("\n", "").replaceAll("\r", "");
}
return "";
}
二、ImageIO两种输出
// 两种方式
ImageIO.write(newBufferedImage, "png", outputStream) // 流
ImageIO.write(newBufferedImage, "png", new File("E:/log/test1.png")) // 文件
三、文件流转BASE64字符串
byte[] bytes = outputStream.toByteArray();
// 转BASE64编码字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64String = encoder.encodeBuffer(bytes).trim();
return base64String.replaceAll("\n", "").replaceAll("\r", "");
前端显示需要追加“data:image/png;base64,” + base64String