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();
}
}
}
添加回答
舉報