/**
* 把网络文件转换为ByteArrayInputStream
*/
public static ByteArrayInputStream networkFileToInputStream(String imageUrl) {
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
try {
//1. 将在线图片地址转换为URL对象
URL url = new URL(imageUrl);
// 打开URL连接
URLConnection connection = url.openConnection();
// 转换为HttpURLConnection对象
HttpURLConnection httpUrlConnection = (HttpURLConnection) connection;
// 获取输入流
inputStream = httpUrlConnection.getInputStream();
//2. 读取输入流中的数据,并保存到字节数组中
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
byteArrayOutputStream.close();
//3. ByteArrayInputStream对象,将字节数组传递给它
byte[] bytes = byteArrayOutputStream.toByteArray();
byteArrayInputStream = new ByteArrayInputStream(bytes);
return byteArrayInputStream;
} catch (IOException ex) {
throw new ServiceException("网络文件转换失效");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error("网络文件转换失效");
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
log.error("网络文件转换失效");
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
log.error("网络文件转换失效");
}
}
}
}
/**
* 网络文件转换为ByteArrayInputStream
* 来自AI豆包
*/
public static ByteArrayInputStream networkFileToInputStreamAi(String imageUrl) {
try (ReadableByteChannel channel = openChannel(imageUrl)) {
ByteBuffer byteBuffer = ByteBuffer.allocate(10240);
while (channel.read(byteBuffer)!= -1) {
// 如果缓冲区已满,进行翻转以准备读取或写入操作
if (byteBuffer.position() == byteBuffer.limit()) {
byteBuffer.flip();
// 扩展缓冲区以容纳更多数据
ByteBuffer newByteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
byteBuffer.flip();
newByteBuffer.put(byteBuffer);
byteBuffer = newByteBuffer;
}
}
// 切换到读模式
byteBuffer.flip();
return new ByteArrayInputStream(byteBuffer.array());
} catch (IOException ex) {
throw new RuntimeException("网络文件转换失效");
}
}
/**
* 打开网络连接并获取可读的字节通道
*/
private static ReadableByteChannel openChannel(String imageUrl) throws IOException {
URL url = new URL(imageUrl);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
return Channels.newChannel(inputStream);
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。