下载网络图片资源:
/**
* 获取网络图
*
* @param url
* @return
*/
public static BufferedImage downloadImage(String url) throws Exception {
log.info("下载网络图片:" + url);
byte[] bytes = HttpsUtils.getBytes(url);
InputStream buffin = new ByteArrayInputStream(bytes, 0, bytes.length);
bytes = null;
BufferedImage result = ImageIO.read(buffin);
return result;
}
直接获取图片信息:
BufferedImage fileStream = ImageEditUtils.downloadImage(pic);
int width = fileStream.getWidth();
int height = fileStream.getHeight();
获取网络图片的宽高:
//获取网络图片的宽高
InputStream is = new URL(url).openStream();
BufferedImage sourceImg = ImageIO.read(is);
int width = sourceImg.getWidth();
int height = sourceImg.getHeight();
双核8G的服务器进行54次的循环时,会出现一下问题:
java.net.ConnectException: Connection timed out (Connection timed out)
原因分析:程序没有关闭连接的原因,当你打开的多了,没关闭连接就会报这个错了。
修改方式一:
URL url = new URL(pic);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
BufferedImage sourceImg = ImageIO.read(connection.getInputStream());
新问题:图片大小超过了可下载量
org.apache.http.ConnectionClosedException: Premature end of Content-Length delimited message body (expected: 860,357; received: 524,288)
解决方式:提供关闭下载连接方式
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class BufferedImageTest {
public static void main(String[] args) {
// 图片路径
String imageURL = "https://visionoss.XXX.com/2f513628-9c77-4f5f-9634-4d69888e6459.jpeg";
BufferedImage image = getRemoteBufferedImage(imageURL);
if (image != null) {
System.out.println("height: " + image.getHeight());
System.out.println("width: " + image.getWidth());
} else {
System.out.println("BufferedImage图片不存在!");
}
}
/**
* 获取远程网络图片信息
* @param imageURL
* @return
*/
public static BufferedImage getRemoteBufferedImage(String imageURL) {
URL url = null;
InputStream is = null;
BufferedImage bufferedImage = null;
try {
url = new URL(imageURL);
is = url.openStream();
bufferedImage = ImageIO.read(is);
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.println("imageURL: " + imageURL + ",无效!");
return null;
} catch (IOException e) {
e.printStackTrace();
System.out.println("imageURL: " + imageURL + ",读取失败!");
return null;
} finally {
try {
if (is!=null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("imageURL: " + imageURL + ",流关闭异常!");
return null;
}
}
return bufferedImage;
}
}