How to ensure that the image is filled? (in java)

i using the code below to get the image at the 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[] picture=tmpOut.toByteArray();
    System.out.println(picture.length);

this code is ok, but my internet connection is very bad,

So maybe I get a broken picture:

alt text

How can I guarantee that the image file is complete?

I think you can add this code to try and verify 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 the help:)

+3
source share
2 answers

Have you studied the ImageIO class for loading images - it takes care of all 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) {
   ...
}
+3
source

Source: https://habr.com/ru/post/1785106/


All Articles