Baixar imagem da internet

Olá amigos.Gostaria de saber como baixar uma imagem da internet através do URL.
Já li sobre a classe java.net.URL,que existe um metodo openStream,mas não sei como usa-lo.

Olha amigos,eu consego agora exibir a imagem.
Usei o seguinte código

 url = new URL("http://images.orkut.com/orkut/photos/OgAAAF2qtz0sgE19qcHfex4G_t9GvNP8Gjv5B4IfwFGBbqBOO2b1it0VEypkd8d5N4yJUI2Ad_wgcFPhzjBZngsNHdUAm1T1UPDtvjzjksyD8QrjxiPVixbqFCWQ.jpg");
        url.openStream();
        imagem = new ImageIcon(url);

        botão = new JButton(imagem);
        add(botão);

ai a imagem é carregada em um JButton.
Mas eu gostaria de baixar a imagem.Usar um JFileChooser para escolher o local onde deseja salvar e salvar.

Visitem o meu blog! :smiley:

A parte do download dá pra fazer assim:

[code]try {

		// 1MB de buffer
		final int BUFFER_SIZE = 1024 * 1024;
		
		String nomeArquivo = "e:/imagem.jpg";

		URL url = new URL(
				"http://images.orkut.com/orkut/photos/OgAAAF2qtz0sgE19qcHfex4G_t9GvNP8Gjv5B4IfwFGBbqBOO2b1it0VEypkd8d5N4yJUI2Ad_wgcFPhzjBZngsNHdUAm1T1UPDtvjzjksyD8QrjxiPVixbqFCWQ.jpg");
	
		BufferedInputStream stream = new BufferedInputStream(
				url.openStream(), BUFFER_SIZE);
		BufferedOutputStream fos = new BufferedOutputStream(
				new FileOutputStream(nomeArquivo));
		byte buf[] = new byte[BUFFER_SIZE];
		int numBytesRead;
		do {
			numBytesRead = stream.read(buf);
			if (numBytesRead > 0) {
				fos.write(buf, 0, numBytesRead);
			}
		} while (numBytesRead > 0);
		fos.flush();
		fos.close();
		stream.close();
		buf = null;

	} catch (MalformedURLException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}[/code]
1 curtida

Obrigado amigo,consegui.
Faz o download perfeitamente.Muito obrigado.

Olá Jamir,

Eu consegui baixar essa imagem http://www.nfe.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image para um JLabel com o código que vc passou,
porém essa imagem muda toda vez que é consultada no navegador, mais no objeto URL parece que ele verifica que é o mesmo e não altera a imagem. Porem se eu fechar o frame e abrir novamente ele atualiza.

Existe alguma forma de limpar o Objeto URL, e fazer uma nova conexão?

Essa é classe que estou usando:

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

/*

  • ImageWeb.java
  • Created on 16/12/2011, 02:50:28
    */
    package teste;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

/**
*

  • @author walter
    */
    public class ImageWeb extends javax.swing.JFrame {

    /** Creates new form ImageWeb */
    public ImageWeb() {
    initComponents();
    }

    private URL downloadImagem(String caminho) {
    URL url = null;
    HttpURLConnection urlConnection = null;
    try {
    url = new URL(caminho);
    urlConnection = (HttpURLConnection) url.openConnection();
    return urlConnection.getURL();
    } catch (IOException ex) {
    Logger.getLogger(ImageWeb.class.getName()).log(Level.SEVERE, null, ex);
    return null;
    } finally {
    urlConnection.disconnect();
    url = null;
    }
    }

    public void atualizaImage(String caminho) {
    ImageIcon imagem = new ImageIcon(downloadImagem(caminho));
    jLabel.setIcon(imagem);
    jLabel.repaint();
    }

    public void atualizaImage1(String caminho) {
    ImageIcon imagem = new ImageIcon(downloadImagem(caminho));
    jLabel1.setIcon(imagem);
    jLabel1.repaint();
    }

    /** This method is called from within the constructor to

    • initialize the form.

    • WARNING: Do NOT modify this code. The content of this method is

    • always regenerated by the Form Editor.
      */
      @SuppressWarnings(“unchecked”)
      //
      private void initComponents() {

      jLabel = new javax.swing.JLabel();
      jbAtualziar = new javax.swing.JButton();
      jLabel1 = new javax.swing.JLabel();

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      getContentPane().setLayout(null);

      jLabel.setBorder(javax.swing.BorderFactory.createTitledBorder(“Imagem de Controle”));
      getContentPane().add(jLabel);
      jLabel.setBounds(12, 12, 281, 174);

      jbAtualziar.setText(“Atualizar”);
      jbAtualziar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      jbAtualziarActionPerformed(evt);
      }
      });
      getContentPane().add(jbAtualziar);
      jbAtualziar.setBounds(12, 192, 72, 30);

      jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(“Imagem de Controle”));
      getContentPane().add(jLabel1);
      jLabel1.setBounds(299, 12, 281, 174);

      pack();
      }//

    private void jbAtualziarActionPerformed(java.awt.event.ActionEvent evt) {
    atualizaImage(“http://www.nfe.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image”);
    atualizaImage1(“http://www.nfe.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image”);
    }

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /
      Set the Nimbus look and feel /
      //
      /
      If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if (“Nimbus”.equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
        }
        }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(ImageWeb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(ImageWeb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(ImageWeb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(ImageWeb.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

      /* Create and display the form */
      java.awt.EventQueue.invokeLater(new Runnable() {

       public void run() {
           new ImageWeb().setVisible(true);
       }
      

      });
      }
      // Variables declaration - do not modify
      private javax.swing.JLabel jLabel;
      private javax.swing.JLabel jLabel1;
      private javax.swing.JButton jbAtualziar;
      // End of variables declaration
      }
      [/code]

Estou a procura de uma solução,

Agradeço desde já.

vlw

Olá, cwegroup,

Tenta desligar o cache da conexão:

private URL downloadImagem(String caminho) { URL url = null; HttpURLConnection urlConnection = null; try { url = new URL(caminho); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); // <---- return urlConnection.getURL(); } catch (IOException ex) { Logger.getLogger(ImageWeb.class.getName()).log(Level.SEVERE, null, ex); return null; } finally { urlConnection.disconnect(); url = null; } }

Boa sorte!

Olá jamir,

O problema foi solucionado com o seguinte codigo:

private URL downloadImagem(String caminho) { URL url = null; HttpURLConnection urlConnection = null; try { url = new URL(caminho); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); // <---- return urlConnection.getURL(); } catch (IOException ex) { Logger.getLogger(ImageWeb.class.getName()).log(Level.SEVERE, null, ex); return null; } finally { urlConnection.disconnect(); url = null; } }

A problema era que na hora de criar um ImageIcon dessa URL, o java não atualizava o objeto por motivo que a URL era a mesma. Assim criei um objeto Image, depois dei um img.flush() no objeto pra depois seta-lo no JLabel:

Image img = new ImageIcon(downloadImagem("http://www.nfe.fazenda.gov.br/scripts/srf/intercepta/captcha.aspx?opt=image", null)).getImage(); img.flush(); jLabel.setIcon(new ImageIcon(img));

Fica registrado para quem tiver o mesmo problema.

Abraço a todos,

Vlw