How to get images on the internet through Java?

1

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

  • www.tempoagr / temp / irati / temp1
  • www.tempoagr / temp / irati / temp2
  • www.tempoagr / temp / irati / temp3

How to do it?

    
asked by anonymous 29.01.2014 / 15:00

5 answers

3

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();
    }
}
    
29.01.2014 / 15:08
2

I think the sample code below can help 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. (World Desktop). With few changes you can adapt it to your need.

Remembering that the code below will "preload" 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.br/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);     
    }
}
    
29.01.2014 / 20:07
0

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 thrown.

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

  • Treat the possible exception if the link is out of order
  • If you are using a GUI (Swing and JavaFX), pick up the image on a new thread so you do not block the application until the download is complete.
29.01.2014 / 15:07
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 you can redirect the output more flexibly than with wget.

Sample java code to run command line programs:

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 the link: link

    
29.01.2014 / 15:11
0

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

Create a Source Folder in your project. Right-click Project > New > Source Folder . Copy your image there. From there, you can internally load 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();

Enjoying, the URLs you posted appear to be local. As a suggestion, post on some image hosting service, such as Snag.gy .

    
29.01.2014 / 15:10