Java操作图片裁剪

前言

Java 操作图片,实现图片的裁剪

裁剪图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class ImageUtil {
/**
* 获取人脸图片数据
*
* @param pictureBytes 照片数据
* @param contentType 请求内容类型
* @param faceName 人脸模型名称
* @return 人脸图片数据
*/
private byte[] getFaceHead(String faceName, byte[] pictureBytes, MediaType contentType) {
/*获取人脸位置与大小*/
double[] faceDetectResult = this.getFaceDetectResult(faceName, pictureBytes, contentType);
if (faceDetectResult[0] == 0
&& faceDetectResult[1] == 0
&& (faceDetectResult[2] == 0
|| faceDetectResult[3] == 0)) {
log.warn("图片无法裁剪,使用原图片");
return pictureBytes;
}
/*裁剪图片*/
try {
/*获取图片 buffer*/
BufferedImage pictureImage = ImageIO.read(new ByteArrayInputStream(pictureBytes));
final int width = pictureImage.getWidth();
final int height = pictureImage.getHeight();
/*图片裁剪*/
int x = (int) (faceDetectResult[0] * width);
/*坐标 - 10*/
x = Math.max((x - 10), 0);
int y = (int) (faceDetectResult[1] * height);
/*坐标 - 10*/
y = Math.max((y - 10), 0);
int w = (int) (faceDetectResult[2] * width);
/*宽度 + 10*/
w = Math.min((w + 10), width - x);
int h = (int) (faceDetectResult[3] * height);
/*高度 + 10*/
h = Math.min((h + 10), height - y);
BufferedImage headImage = pictureImage.getSubimage(x, y, w, h);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(headImage, "jpg", out);
return out.toByteArray();
} catch (IOException e) {
log.warn("裁剪图片失败使用原照片 {}", e.getMessage());
throw new RuntimeException("裁剪图片失败");
}
}
}

附录

1 图片操作类

  1. Image
  2. BufferedImage
    1. getSubimage 图片裁剪
  3. ImageIO
    1. read 读取图片
    2. wirte 写出图片

本文地址: https://github.com/maxzhao-it/blog/post/8bda86f4/