2 回答
TA贡献1828条经验 获得超13个赞
在保存之前,您可以在 Rest Service 中将图像 url 转换为数据字节 [] 图像。
public static byte[] convertImageByte(URL url) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
return byteChunk;
}
catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
// Perform any other exception handling that's appropriate.
}
finally {
if (is != null) { is.close(); }
}
return null;
}
TA贡献1811条经验 获得超4个赞
好的问题解决了。将图像 URL 转换为字节数组的代码如下。有关此问题的更多答案,请参阅此处
public static byte[] convertImageByte(URL url) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = new BufferedInputStream(url.openStream());
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
return baos.toByteArray();
}
catch (IOException e) {e.printStackTrace ();}
finally {
if (is != null) { is.close(); }
}
return null;
}
将 Dto 保存到数据库时
if(dto.getImageUrl() != null) {
try {
URL imageUrl = new URL(dto.getImageUrl());
itemDO.setImage(convertImageByte(imageUrl));
} catch (IOException e) {
e.printStackTrace();
}
}
entity = orderItemRepository.save(itemDO);
从数据库中获取图像
public byte[] getImageForOrderItem(long itemId) {
Optional<OrderItemDO> option = orderItemRepository.findById(itemId);
if(option.isPresent()) {
OrderItemDO itemDO = option.get();
if(itemDO.getImage() != null) {
byte[] image = itemDO.getImage();
return image;
}
}
return null;
}
通过 Rest API 调用 Image Response
@GetMapping(path="/orderItem/image/{itemId}")
@ResponseStatus(HttpStatus.OK)
public void getImageForOrderItem(@PathVariable("itemId") long itemId, HttpServletResponse response) {
byte[] buffer = orderServiceImpl.getImageForOrderItem(itemId);
if (buffer != null) {
response.setContentType("image/jpeg");
try {
response.getOutputStream().write(buffer);
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
添加回答
举报