简体   繁体   English

如何确保我的图片完整? (在java中)

[英]How to ensure I get the picture is complete? (in java)

i using below code to get a picture from URL: 我使用下面的代码从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 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 ) { 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: 您是否考虑过使用ImageIO类加载图像 - 它会为您处理很多这些细节:

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() ). 尝试使用URL.openConnection()代替您获得一个URLConnection对象,您可以在其上查询内容长度(如果提供)( 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. 在另一种情况下,您可以分析图像标题以获得其长度,但这需要为每种格式使用专用分析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM