需求:接收到其他服务发送过来的base64的图片,然后给了个截图的4个点的坐标,现在需要根据4个点的坐标,进行截图之后返回到前端去显示出来;主要使用BufferedImage的getSubimage方法;如下所示
1>构造个对象封装下这几个参数,从其他服务中接受到数据格式为图片的四个点坐标的一个二维数组,需要转换为截图的点x坐标,y坐标,截图的宽度和高度;所以先封装个对象;通过一个二维数组计算出这些参数:
class ImageInfo {
private int x;
private int y;
private int width;
private int height;
public ImageInfo(String[][] position) {
String[] strings = position[0];
int x = Integer.parseInt(strings[0]);
int y = Integer.parseInt(strings[1]);
String[] forthPoint = position[2];
int x1 = Integer.parseInt(forthPoint[0]);
int y1 = Integer.parseInt(forthPoint[1]);
this.x = x;
this.y = y;
this.width = x1 - x;
this.height = y1 - y;
}
}
2>转换的主要代码
public String getSubImage(String sourceImage, String[][] positions) throws IOException {
ImageInfo imageInfo = new ImageInfo(positions);
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(sourceImage);
ByteArrayInputStream inputStream = new ByteArrayInputStream(b);
BufferedImage bi = ImageIO.read(inputStream);
BufferedImage subimage = bi.getSubimage(imageInfo.x, imageInfo.y, imageInfo.width, imageInfo.height);
return bufferImageToBase64(subimage);
}
主要构造一个BufferedImage对象,然后调用getSubimage方法,结果返回一个BufferedImage对象;最后再把BufferedImage转换成base64字符串返回;
3>bufferImageToBase64方法
private String bufferImageToBase64(BufferedImage bufferedImage) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
byte[] bytes = baos.toByteArray();
String trim = encoder.encodeBuffer(bytes).trim();
return trim.replaceAll("\n", "").replaceAll("\r", "");
}
最后要注意的是,最后要进行空格字符的替换;不然显示不正确的;
4>encoder对象主要用来解码使用;
static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
5>前端显示使用下面格式,然后后面跟上返回的内容;
<img src="data:image/jpeg;base64,