How to pick up images on the internet through Java?

Asked

Viewed 4,549 times

1

I am very beginner in Java and need to get some images from the internet to insert in my project (there are 5 images). Follow example links:

  • www.tempoagr/tempo/Irati/temp1
  • www.tempoagr/tempo/Irati/temp2
  • www.tempoagr/tempo/Irati/temp3

How to do?

  • Do you want to download the images while running the program , or download now to insert the image into your project? Obs: the links of the images you posted are not available (should be only in your network)

  • 2

    Explain better what you want to do and post code too.

5 answers

4


See if this works for you:

URL urlObj = new URL(//img que vc quer baixar.);                                    
HttpURLConnection  httpConnection = (HttpURLConnection)urlObj.openConnection();
httpConnection.setRequestMethod("GET");
InputStream inputStream = httpConnection.getInputStream();
OutputStream outputStream = null;
try {
    int read = 0;
    byte[] bytes = new byte[1024];
    outputStream = new FileOutputStream(new File(pathToSave));
    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
} catch (FileNotFoundException ex) {
    ex.getMessage();
} catch (IOException ex) {
    ex.getMessage();
} finally {
    try {
        if (outputStream != null) {
            outputStream.close();
        }
    } catch (IOException ex) {
        ex.getMessage();
    }
}

3

I believe the sample code below can help you, if your project is "Desktop or Applet", programmed through the Swing API.

The code example below will download the Google logo and display it on the screen, through a swing component. That nothing else is a way to manipulate graphical applications in Java. (Desktop World). With few changes you can adapt it to your need.

Remembering that the code below will make a "Preload" of the image before it is displayed.

import java.awt.FlowLayout;
import java.awt.MediaTracker;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Stackoverflow2673 {

    public static void main(String[] args) throws MalformedURLException {

        JFrame frame = new JFrame(); // cria frame (janela)
        // seta preferencias do frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(580, 250);

        // inicializa painel
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout());

        // inicializa label
        JLabel lblImg = new JLabel(); 

        // inicializa a imagem URL dentro de um objeto ImageIcon
        URL urlImg = new URL("https://www.google.com/images/srpr/logo11w.png");
        ImageIcon imgIcon = new ImageIcon(urlImg);
        // faz o preload da imagem
        while(imgIcon.getImageLoadStatus() == MediaTracker.LOADING); 

        // injeta o icone no label
        lblImg.setIcon(imgIcon);
        // adicina o label no panel
        p.add(lblImg);

        frame.getContentPane().add(p);

        // abre a janela (frame)
        frame.setVisible(true);     
    }
}

1

Using java.net.URL, java.awt.Image and javax.imageio.ImageIO:

Url url = new URL("http://www.tempoagr/tempo/irati/temp1");
Image imagem = ImageIO.read(url);

Remember that for this to work the URL must be valid, or an exception will be "move".

Of course, this is in case you want to get the image INSIDE the program. If so, it has much more complexity:

  • Treat the possible exception if the link is out of order
  • If you are using a graphical interface (Swing and Javafx type), take the image in a new thread to not block the application until the download is completed

0

If you are trying to include an image to your program at design time, you can do it as follows in Eclipse:

Create a Source Folder in your project. Right click on Project > New > Source Folder. Copy your image there. From there, you can internally upload the image as follows:

InputStream input = classLoader.getResourceAsStream("arquivo.ext");

If you want to do this programmatically, you have at least two options:

Via javax.imageio:

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

Via Sockets/stream:

URL url = new URL("http://www.website.com/arquivo.ext");
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://arquivo.ext");
fos.write(response);
fos.close();

Taking advantage, the Urls you posted seem to be local. As a suggestion, post in some image hosting service, as the Snag.Gy.

0

If you are running on a Unix operating system like you make a call within java using your system’s command line tools.

GET http://www.weronline.com/nuno/varios/imagens/teste1.jpg HTTP/1.0 > teste.jpeg

or

wget http://www.weronline.com/nuno/varios/imagens/teste1.jpg

Both commands will save the link image, but with GET vc you can redirect the output more flexibly than with wget.

Example java code to execute command line prograamas:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("GET http://www.weronline.com/nuno/varios/imagens/teste1.jpg HTTP/1.0 > teste.jpeg");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}
    }
}

PS: Java example taken from link:https://stackoverflow.com/questions/3403226/how-to-run-linux-commands-in-java-code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.