英文:
how insert image from db to page in thymeleaf
问题
以下是你要翻译的内容:
"I can't understand how send to browser my image from server. My code down below. Why it doesn't working? When I'm getting bytes from DB and save them to disk image opens fine.
In html there is next code:
<div th:fragment="image_list">
image will be here
<p>
<img class="picture" th:src="@{/image/1}"/>
</div>
Java controller class:
@GetMapping(value = "/{id}")
@ResponseBody
public ResponseEntity<InputStreamResource> getCarImage(@PathVariable Long id) {
var image = imageService.getOne(id);
var imageDecompressed = decompressBytes(image.getImage());
InputStream inputStream = new ByteArrayInputStream(imageDecompressed);
return ResponseEntity.ok()
.contentLength(image.getImage().length)
.contentType(MediaType.IMAGE_JPEG)
.body(new InputStreamResource(inputStream));
}
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
英文:
I can't understand how send to browser my image from server. My code down below. Why it doesn't working? When I'm getting bytes from DB and save them to disk image opens fine.
In html there is next code:
<div th:fragment="image_list">
image will be here
<p>
<img class="picture" th:src="@{/image/1}"/>
</div>
Java controller class:
@GetMapping(value = "/{id}")
@ResponseBody
public ResponseEntity<InputStreamResource> getCarImage(@PathVariable Long id) {
var image = imageService.getOne(id);
var imageDecompressed = decompressBytes(image.getImage());
InputStream inputStream = new ByteArrayInputStream(imageDecompressed);
return ResponseEntity.ok()
.contentLength(image.getImage().length)
.contentType(MediaType.IMAGE_JPEG)
.body(new InputStreamResource(inputStream));
}
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
答案1
得分: 1
使用此示例
@ResponseBody
@GetMapping(value = "/{id}")
public byte[] getImageAsByteArray(@PathVariable int id) {
return imageService.getOne(id).getImage();
}
英文:
Using this sample
@ResponseBody
@GetMapping(value = "/{id}")
public byte[] getImageAsByteArray(@PathVariable int id) {
return imageService.getOne(id).getImage();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论