如何从java中的任何网页下载图像

时间:2023-01-24 16:20:43

hi I am trying to download image from web page. I am trying to download the image from 'http://www.yahoo.com' home page. Please tell me how to pass 'http://www.yahoo.com' as a input. And on opening this web page how to fetch image from this page. Please give me java code to fetch the image from web page.

嗨,我试图从网页下载图像。我试图从'http://www.yahoo.com'主页下载图像。请告诉我如何通过'http://www.yahoo.com'作为输入。在打开此网页时,如何从此页面获取图像。请给我java代码从网页上获取图片。

7 个解决方案

#1


116  

(throws IOException)

Image image = null;
try {
    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

有关详细信息,请参阅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();

And you may then want to save the image so do:

然后你可能想要保存图像,所以:

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

#2


26  

If you want to save the image and you know its URL you can do this:

如果要保存图像并且知道其URL,则可以执行以下操作:

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

You will also need to handle the IOExceptions which may be thrown.

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

#3


8  

It works for me)

这个对我有用)

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();

#4


6  

You are looking for a web crawler. You can use JSoup to do this, here is basic example

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

#5


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();
}

#6


0  

The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources.

以下代码将图像从磁盘的直接链接下载到项目目录中。另请注意,它使用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);
            }
        }
    }
}

#7


-1  

I think he wanted to give site's url as input, NOT image url. For images that have their url as src in sites html code, I think you could do prasing and look for <img ... src=, and if it is url and not local path, use the methodes in other answers to save it.

我想他想把网站的网址作为输入,而不是图片网址。对于在网站html代码中将其url作为src的图像,我认为你可以进行prasing并查找如何从java中的任何网页下载图像

#1


116  

(throws IOException)

Image image = null;
try {
    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

有关详细信息,请参阅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();

And you may then want to save the image so do:

然后你可能想要保存图像,所以:

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

#2


26  

If you want to save the image and you know its URL you can do this:

如果要保存图像并且知道其URL,则可以执行以下操作:

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

You will also need to handle the IOExceptions which may be thrown.

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

#3


8  

It works for me)

这个对我有用)

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();

#4


6  

You are looking for a web crawler. You can use JSoup to do this, here is basic example

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

#5


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();
}

#6


0  

The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources.

以下代码将图像从磁盘的直接链接下载到项目目录中。另请注意,它使用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);
            }
        }
    }
}

#7


-1  

I think he wanted to give site's url as input, NOT image url. For images that have their url as src in sites html code, I think you could do prasing and look for <img ... src=, and if it is url and not local path, use the methodes in other answers to save it.

我想他想把网站的网址作为输入,而不是图片网址。对于在网站html代码中将其url作为src的图像,我认为你可以进行prasing并查找如何从java中的任何网页下载图像