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
49
50
51
52
53
public class ImageUtil {
/**
* 测试
*/
public void test() {
try {
FileInputStream in = new FileInputStream("D:\\Pictures\\temp\\1.jpg");
byte[] bytes = new byte[in.available()];
int read = in.read(bytes);
in.close();
bytes = getFaceHead(getFaceHead);
OutputStream outputStream = new FileOutputStream("D:\\Pictures\\temp\\" + System.currentTimeMillis() + ".jpg");
outputStream.write(bytes);
outputStream.close();
} catch (Exception e) {
throw new RuntimeException("翻转图片失败");
}
}

/**
* 水平翻转图片
*
* @param pictureBytes 照片数据
* @return 人脸图片数据
*/
private byte[] getFaceHead(byte[] pictureBytes) {
/*翻转图片*/
try {
/*获取图片 buffer*/
BufferedImage pictureImage = ImageIO.read(new ByteArrayInputStream(pictureBytes));
final int width = pictureImage.getWidth();
final int height = pictureImage.getHeight();
/*读取所有的像素*/
int[] rgbs = pictureImage.getRGB(0, 0, width, height, null, 0, width);
/*水平切换像素*/
int temp;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width / 2; col++) {
temp = rgbs[row * width + col];
rgbs[row * width + col] = rgbs[row * width + (width - 1 - col)];
rgbs[row * width + (width - 1 - col)] = temp;
}
}
/*写入像素*/
pictureImage.setRGB(0, 0, width, height, rgbs, 0, width);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(pictureImage, "jpg", out);
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("翻转图片失败");
}
}
}

附录

1 图片操作类

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

本文地址: https://github.com/maxzhao-it/blog/post/1a9b93f6/