使用ImageIO读取网络图片或本地图片

来自网络

读取网络图片

1
2
URL url = new URL(path);
BufferedImage source= ImageIO.read(url);

读取本地图片

1
BufferedImage source= ImageIO.read(new File(path));

获取网络图片工具类

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42

public class HttpImageUtils {

private static final Logger logger = LoggerFactory.getLogger(HttpImageUtils.class);
public static final int TIMEOUT = 5 * 1000;

/**
* 获取网络图片转成字节流
* @param strUrl 完整图片地址
* @return 图片资源数组
*/
public static byte[] getNetImgByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(TIMEOUT);
InputStream inStream = conn.getInputStream();
return readInputStream(inStream);
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return null;
}

/**
* 从输入流中获取字节流数据
* @param inStream 输入流
* @return 图片流
*/
private static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[Integer.MAX_VALUE];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}


使用ImageIO读取网络图片或本地图片
https://cason.work/2022/07/19/使用ImageIO读取网络图片或本地图片/
作者
Cason Mo
发布于
2022年7月19日
许可协议