2

我有一种从 URL 下载图像的方法。如下图。。

public static byte[] downloadImageFromURL(final String strUrl) {
    InputStream in;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        URL url = new URL(strUrl);
        in = new BufferedInputStream(url.openStream());
        byte[] buf = new byte[2048];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
    }
    catch (IOException e) {
        return null;
    }
    return out.toByteArray();
}

我有一个图片网址,它是有效的。例如。

https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcg

我的问题是,如果图像真的不存在,我不想下载。喜欢....

https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcgaaaaaabbbbdddddddddddddddddddddddddddd

此图像不应该通过我的方法下载。那么,我怎么知道给出的图像 URL 并不存在。我不想验证我的 URL(我认为这可能不是我的解决方案)。

所以,我用谷歌搜索。从这篇文章...... 如何检查一个URL是否存在或使用Java返回404?使用其 URL 检查远程服务器上是否存在文件

但是这个 con.getResponseCode() 将始终返回状态代码“200”。这意味着我的方法也会下载无效的图片 url。所以,我输出我的bufferStream就像......

System.out.println(in.read(buf));

无效的图像 URL 生成“43”。所以,我在我的方法中添加了这些代码行。

    if (in.read(buf) == 43) {
       return null;
    }

没关系。但我认为这不会总是令人满意。有没有其他方法可以得到它?我对吗?我真的很感激任何建议。这个问题可能会影响我的头脑。感谢您阅读我的问题。

*更新

我称这种下载方法并将下载的图像保存在某个目录中为..

            // call method to save image
            FileSupport.saveFile(filePath+".JPG", data);

之后我尝试输出为...

            File file = new File(filePath+".JPG);
            System.err.println(file.length());

这也可能为无效的图像 url产生“43 ”。我想知道为什么所有无效网址都返回“43”。什么是“43”

4

4 回答 4

3

试试这个,

在记事本或其他东西中打开图像并检查前 3-4 个字符,它会告诉您图像的格式..

下载时检查前 3 或 4 个字符,这应该会告诉您此图像是否有效。

注意:在这里,我假设您的要求特定于某些类型的图像,而不是所有可能的图像。

一些样品:

‰PNG 用于 PNG 图像 ����JFIF 用于 JPG 图像。

byte[] tenBytes=new byte[10];
// fill this array with the first 10 bytes.
String str = new String(tenBytes);
if(str.contains("JIFF")){
// JPG
}
if(str.contains("PNG"){
// PNG
} ...

如果没有匹配,它要么是无效图像,要么是您不想要的图像。

请注意,这是未经测试的代码。您可能需要对其进行调整才能正常工作。你应该把它看作是一个伪代码来构建你的实现......

更新:您应该寻找内容(如上所述),而不是检查文件大小 43。

于 2013-10-26T05:03:10.960 回答
1

如果

con.setRequestMethod("HEAD");

对您没有帮助,您应该执行以下操作(如果图像不存在,则从连接的输入流中读取将失败。

  HttpUrlConnection con = (HttpUrlConnection)url.openConnection;
  con.setRequestMethod("GET");
  con.addRequestProperty("User-Agent", "Mozilla/4.0");

  int responseCode = con.getResponseCode(); //if you do not get 200 here, you can stop

  if(responseCode != HttpUrlConnection.HTTP_OK) {
    return;
  }
  // Now, read image buffer
  byte[] image = null;

  try{

       InputStream in = new BufferedInputStream(con.getInputStream());
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       byte[] buf = new byte[1024];

       int n = 0;

       while (-1!=(n=in.read(buf)))
       {
          out.write(buf, 0, n);
       }
       out.close();
       in.close();
       image = out.toByteArray();

    } catch (IOException ioe){
       // do whatever you need
    } finally {
       con.disconnect();
    }

另外,这段代码

 if (in.read(buf) == 43) {
       return null;
 }

看起来不太好。一些神奇的数字,不清楚它是什么。

于 2013-10-26T03:43:00.627 回答
0

我会这样做:

//By Nishanth Chandradas

import java.awt.Image;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.activation.MimetypesFileTypeMap;
import javax.swing.ImageIcon;

import java.io.File;

public class downloadimagefromurl {

    /**
     * @param args
     * @throws IOException 
     */

    public static byte[] downloadImageFromURL(final String strUrl) throws IOException {
        InputStream in;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            URL url = new URL(strUrl);
            in = new BufferedInputStream(url.openStream());
            byte[] buf = new byte[2048];
            int n = 0;
            while (-1 != (n = in.read(buf))) {
                out.write(buf, 0, n);
            }
            out.close();
            in.close();
        }
        catch (IOException e) {
            return null;
        }
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream("/Users/Nish/Desktop/image.jpg");
        fos.write(response);
        fos.close();
        return response;
    }

    static boolean isImage(String image_path){
          Image image = new ImageIcon(image_path).getImage();
          if(image.getWidth(null) == -1){
                return false;
          }
          else{
                return true;
          }
        }

    public static void main(String[] args) throws IOException {
        downloadImageFromURL("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTxfYM-hnD-Z80tgWdIgQKchKe-MXVUfTpCw1R5KkfJlbRbgr3Zcg");
     System.out.println(isImage("/Users/Nish/Desktop/image.jpg"));
    }

输出将是真或假,具体取决于下载是否为图像。

于 2013-10-26T03:22:37.553 回答
-1

您可以添加第二个 catch 语句来捕获 java.io.FileNotFoundException

catch (FileNotFoundException e) {
    // Failed
}
于 2013-10-26T03:08:16.067 回答