如何确保我的照片完整?
问题描述:
我用下面的代码从URL的图片(在Java中):如何确保我的照片完整?
URL url=new URL("http://www.google.com/images/logos/ps_logo2.png");
InputStream in=url.openStream();
ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len;
while (true) {
len = in.read(buf);
if (len == -1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
byte[] picture=tmpOut.toByteArray();
System.out.println(picture.length);
这段代码是好的,但我的互联网连接是非常非常糟糕,
所以,我可能得到一个破碎的画面像这样:
我怎样才能确保图片文件是否已经完成?
我想你可以添加该代码尝试和测试:
if (len == -1) {
变化if (len == -1 || (int)(Math.random()*100)==1) {
完整的测试代码:
URL url=new URL("http://www.google.com/images/logos/ps_logo2.png");
InputStream in=url.openStream();
ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int len;
while (true) {
len = in.read(buf);
if (len == -1 || (int)(Math.random()*100)==1) {
break;
}
tmpOut.write(buf, 0, len);
}
tmpOut.close();
byte[] picture =tmpOut.toByteArray();
System.out.println(picture.length);
感谢帮助:)
答
有你看着使用ImageIO类加载图像 - 它照顾了很多这些细节的你:
Image image;
try {
URL url = new URL("http://www.google.com/images/logos/ps_logo2.png");
image = ImageIO.read(url);
} catch (IOException e) {
...
}
答
尝试使用URL.openConnection()而不是 您会得到一个URLConnection对象,您可以在其中q用尽内容长度(如果提供)(URLConnection.getContentLength())。这在大多数情况下都会有帮助。
在另一种情况下,您可以分析图像标题以获取其长度,但这需要每种格式的专用分析器。