图片操作

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
@GetMapping("/image/{path}")
public void getImage(@PathVariable String path, HttpServletResponse response) throws IOException {
System.out.println("path的值:" + path);
System.out.println("开始加载图片" + path);
try {
// 图片文件的路径,这里假设图片存放在项目根目录下的 images 文件夹中
String imagePath = "./uploads/" + path;
System.out.println(imagePath);
File imageFile = new File(imagePath);

// 检查文件是否存在

// 读取图片文件内容
InputStream inputStream = new FileInputStream(imageFile);
byte[] imageBytes = new byte[(int) imageFile.length()];
inputStream.read(imageBytes);
inputStream.close();

// 设置响应头
response.setContentType(MediaType.IMAGE_JPEG.toString()); // 根据实际图片类型设置
response.setContentLength(imageBytes.length);
Files.copy(imageFile.toPath(), response.getOutputStream());

// 返回响应实体
} catch (IOException e) {
e.printStackTrace();
}
}