How to ensure I get the picture is complete? (in java)
i using below code to get a picture from URL:
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[] pictur开发者_开发技巧e=tmpOut.toByteArray();
System.out.println(picture.length);
this code is okay,but my internet connect is very very bad,
so ,I maybe get a broken picture like this:
How can I ensure the picture file is complete ?
I think you can add this code to try and test this:
if (len == -1) {
change to if (len == -1 || (int)(Math.random()*100)==1 ) {
full test code:
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);
thanks for help :)
Have you looked into using the ImageIO class for loading images - it takes care of a lot of these details for you:
Image image;
try {
URL url = new URL("http://www.google.com/images/logos/ps_logo2.png");
image = ImageIO.read(url);
} catch (IOException e) {
...
}
Try using URL.openConnection() instead You get an URLConnection object on which you can query the content length (if provided) (URLConnection.getContentLength()). That would help in most case.
In the other case you can analyze the image header to get its length, but that would require a dedicated analyzer for each format.
精彩评论