【问题标题】:how to download image from any web page in java如何从java中的任何网页下载图像
【发布时间】:2011-08-18 10:17:13
【问题描述】:

嗨 我正在尝试从网页下载图像。 我正在尝试从“http://www.yahoo.com”主页下载图像。 请告诉我如何通过“http://www.yahoo.com”作为输入。 并在打开此网页时如何从该页面获取图像。 请给我 java 代码以从网页中获取图像。

【问题讨论】:

    标签: java html download


    【解决方案1】:
    try (URL url = new URL("http://www.yahoo.com/image_to_read.jpg")) {
        Image image = ImageIO.read(url);
    } catch (IOException e) {
        // handle IOException
    }
    

    请参阅javax.imageio 包了解更多信息。那是使用 AWT 图像。否则你可以这样做:

    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    InputStream in = new BufferedInputStream(url.openStream());
    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();
    byte[] response = out.toByteArray();
    

    然后您可能想要保存图像,这样做:

    FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
    fos.write(response);
    fos.close();
    

    【讨论】:

    • 对于Java7修改代码sn-p使用try-with-resources语句,见docs.oracle.com/javase/tutorial/essential/exceptions/…
    • 只是一个想法,因为我无法使用包装在 FileInputStream 下的标准 InputStreamReader 保存文件以获取远程 URL。我得到了文件,但它无效。为什么会这样?
    【解决方案2】:

    如果你想保存图片并且知道它的 URL,你可以这样做:

    try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
        Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
    }
    

    您还需要处理可能被抛出的IOExceptions。

    【讨论】:

    • @carlosavoy Java,特别是 Java 8,我认为它也可以在 Java 7 中使用,但我还没有尝试过。 idk 关于 android。
    【解决方案3】:
       // Do you want to download an image?
       // But are u denied access?
       // well here is the solution.
    
        public static void DownloadImage(String search, String path) {
    
        // This will get input data from the server
        InputStream inputStream = null;
    
        // This will read the data from the server;
        OutputStream outputStream = null;
    
        try {
            // This will open a socket from client to server
            URL url = new URL(search);
    
           // This user agent is for if the server wants real humans to visit
            String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
    
           // This socket type will allow to set user_agent
            URLConnection con = url.openConnection();
    
            // Setting the user agent
            con.setRequestProperty("User-Agent", USER_AGENT);
    
            // Requesting input data from server
            inputStream = con.getInputStream();
    
            // Open local file writer
            outputStream = new FileOutputStream(path);
    
            // Limiting byte written to file per loop
            byte[] buffer = new byte[2048];
    
            // Increments file size
            int length;
    
            // Looping until server finishes
            while ((length = inputStream.read(buffer)) != -1) {
                // Writing data
                outputStream.write(buffer, 0, length);
            }
        } catch (Exception ex) {
            Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
         }
    
         // closing used resources
         // The computer will not be able to use the image
         // This is a must
    
         outputStream.close();
         inputStream.close();
    }
    

    【讨论】:

    • 您能在答案中添加一些 cmets 吗?
    • 什么意思??
    • 您如何知道要使用的缓冲区大小?这里你使用了 2048 字节,但你怎么知道不使用 1028 或 4100?
    • 如何确定 URL 连接的用户代理字符串?有没有为此制定的标准?
    • 这是此答案的关键线,其他答案未能解决。 String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
    【解决方案4】:

    这对我有用:

    URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
    InputStream in = new BufferedInputStream(url.openStream());
    OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));
    
    for ( int i; (i = in.read()) != -1; ) {
        out.write(i);
    }
    in.close();
    out.close();
    

    【讨论】:

      【解决方案5】:

      您正在寻找网络爬虫。您可以使用JSoup 来执行此操作,here 是基本示例

      【讨论】:

        【解决方案6】:

        以下代码将图像从磁盘的直接链接下载到项目目录中。另请注意,它使用try-with-resources

        import java.io.BufferedInputStream;
        import java.io.BufferedOutputStream;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.OutputStream;
        import java.net.MalformedURLException;
        import java.net.URL;
        
        import org.apache.commons.io.FilenameUtils;
        
        public class ImageDownloader
        {
            public static void main(String[] arguments) throws IOException
            {
                downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
                        new File("").getAbsolutePath());
            }
        
            public static void downloadImage(String sourceUrl, String targetDirectory)
                    throws MalformedURLException, IOException, FileNotFoundException
            {
                URL imageUrl = new URL(sourceUrl);
                try (InputStream imageReader = new BufferedInputStream(
                        imageUrl.openStream());
                        OutputStream imageWriter = new BufferedOutputStream(
                                new FileOutputStream(targetDirectory + File.separator
                                        + FilenameUtils.getName(sourceUrl)));)
                {
                    int readByte;
        
                    while ((readByte = imageReader.read()) != -1)
                    {
                        imageWriter.write(readByte);
                    }
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-31
          • 2019-11-25
          • 1970-01-01
          • 2016-03-15
          • 1970-01-01
          • 1970-01-01
          • 2012-01-28
          • 1970-01-01
          相关资源
          最近更新 更多