方式1
/**
* 获取网络图片的byte数组
* @param imageUrl
* @return
*/
public byte[] getImageBytes(String imageUrl) {
try {
URL url = new URL(imageUrl);
try (InputStream inputStream = url.openStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096];
int n;
while ((n = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, n);
}
return outputStream.toByteArray();
}
} catch (Exception e) {
log.info("获取URL图片byte数组异常:{}",e);
return null;
}
}
方式2
/**
* 获取网络图片的byte数组
* @param imageUrl
* @return
*/
public byte[] getImageBytes(String imageUrl) {
ByteArrayOutputStream baos = null;
try {
URL u = new URL(imageUrl);
BufferedImage image = ImageIO.read(u);
//convert BufferedImage to byte array
baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
log.info("获取URL图片byte数组异常:{}",e);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
}
}
}
return null;
}