[RESOLVIDO]upload de imagem desktop

6 respostas
maiden

Tenho a seguinte classe:

package view.gui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CapturarImagem extends JFrame implements ActionListener{

	public CapturarImagem(){
		
		super("Capturando Imagem");
		
		JButton botao = new JButton("Abrir Arquivo");
		botao.setFont(new Font("Serif", Font.PLAIN, 26));
		botao.addActionListener(this);
		
		Container c = getContentPane();
		c.add(BorderLayout.NORTH, botao);
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 500);
		setVisible(true);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		JFileChooser c = new JFileChooser();
		c.showOpenDialog(this);//abre o arquivo
		File file = c.getSelectedFile();//abre o arquivo selecionado
		
		try{
			
			Path path = Paths.get(file.getAbsolutePath());
			
		}catch(Exception e1){
			JOptionPane.showMessageDialog(this, "Não obteve o carregamento do arquivo");
		}
	}
	
	public static void main(String[] args) {
		
		new CapturarImagem();
	}
	
}

Minha duvida é como carregar um arquivo de imagem, mas o que quero saber mesmo é:

em um formulário o que seria melhor colocar a imagem no banco de dados e carregar ela quando fazer o select ou é melhor carregando em uma label ou carregar o arquivo de Imagem?

6 Respostas

maiden

Tentei colocar assim:

try{
			
			Path path = Paths.get(file.getAbsolutePath());
			ImageIcon icon = 
					new ImageIcon(getClass().getResource("fotos/quebradebraço.jpg"));
			
		}catch(Exception e1){
			JOptionPane.showMessageDialog(this, "Não obteve o carregamento do arquivo");
		}

mas tambem não deu certo

maiden

Dei uma pesquisada e vi esse tutorial
http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html

e troquei o código no try…catch mas também não deu certo alguém pode de dar uma help?

BufferedImage img;//ta como atributo

                try{
			
			Path path = Paths.get(file.getAbsolutePath());
			img = ImageIO.read(new File("fotos/arvore.jpg"));
			
		}catch(Exception e1){
			JOptionPane.showMessageDialog(this, "Não obteve o carregamento do arquivo");
		}
maiden

seguindo o tutorial que passei deu certo fazer a leitura:

package iocompornentes;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

/**
 * This class demonstrates how to load an Image from an external file
 * http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html
 */
public class LoadImageApp extends Component {
          
    BufferedImage img;

    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }

    public LoadImageApp() {
      
    	try {
    	   
    	   img = ImageIO.read(new File("C:/Users/willame/git/UniversidadeXti/src/view/gui/fotos/arvore.jpg"));
    	   
       } catch (IOException e) {
    	   e.printStackTrace();
       }

    }

    public Dimension getPreferredSize() {
        if (img == null) {
             return new Dimension(100,100);
        } else {
           return new Dimension(img.getWidth(null), img.getHeight(null));
       }
    }

    public static void main(String[] args) {

        JFrame f = new JFrame("Load Image Sample");
            
        f.addWindowListener(new WindowAdapter(){
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });

        f.add(new LoadImageApp());
        f.pack();
        f.setVisible(true);
    }
}

Aqui faz a leitura corretamente fazendo o caminho corretamente onde fica a imagem img = ImageIO.read(new File(“C:/Users/willame/git/UniversidadeXti/src/view/gui/fotos/arvore.jpg”));

mas quando coloco esse mesmo caminho no código usando JFileChooser não funciona o carregamento da imagem, alguém sabe me dizer o porquê?

maiden

Na classe JFileChooser coloquei uma condição para a referencia img, e essa img está vindo null, mas estou inicializando a img isso que não to entendendo…

public void actionPerformed(ActionEvent e) {
		
		JFileChooser c = new JFileChooser();
		c.showOpenDialog(this);//abre o arquivo
		File file = c.getSelectedFile();//abre o arquivo selecionado
		
		try{
			
			if(img != null){
				img = ImageIO.read(new File("C:/Users/willame/git/UniversidadeXti/src/view/gui/fotos/arvore.jpg"));
			}else{
				JOptionPane.showMessageDialog(this, "Imagem não encotrada");
			}
			
		}catch(Exception e1){
			e1.printStackTrace();
			JOptionPane.showMessageDialog(this, "Não obteve o carregamento do arquivo");
		}
	}
maiden

vi que a img tava vindo null mudei a posição conforme exibe logo abaixo, mas mesmo assim a imagem não carregou isso significa que img = ImageIO.read(new File(“C:/Users/willame/git/UniversidadeXti/src/view/gui/fotos/arvore.jpg”)); não está fazendo a leitura da imagem agora queria saber o porquê?

try{
			
			img = ImageIO.read(new File("C:/Users/willame/git/UniversidadeXti/src/view/gui/fotos/arvore.jpg"));
			
			if(img != null){
				JOptionPane.showMessageDialog(this, "Imagem carregada com sucesso!");
			}else{
				JOptionPane.showMessageDialog(this, "Imagem não encotrada");
			}
			
		}catch(Exception e1){
			e1.printStackTrace();
			JOptionPane.showMessageDialog(this, "Não obteve o carregamento do arquivo");
		}
maiden

Modifiquei a classe seguindo os seguintes tutoriais: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
http://stackoverflow.com/questions/10737029/image-loading-using-a-jfilechooser-into-a-jframe
http://javafree.uol.com.br/topic-893721-upload-de-imagem-desktop.html

Ninguém aqui no fórum me ajudou, mas deu para resolver o problema o código final logo abaixo:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;

//carrega a imagem na mesma janela do botão
@SuppressWarnings("serial")
public class CapturarImagem2 extends JFrame implements ActionListener{
	
	JFileChooser chooser;
    BufferedImage img;
	JButton button2;
    File file ; 
    JLabel label; 

	public CapturarImagem2(){
		
		super("Capturar Imagem");
		
		setSize(450,450);//tamanho da janela

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        getContentPane().add(panel);
		
		chooser = new JFileChooser();
		
		label = new JLabel();

	    JPanel secpanel = new JPanel();
	    setVisible(true);

	    JRootPane compPane = panel.getRootPane();
	    Container contePane = compPane.getContentPane();
	    contePane.add(secpanel);

	    secpanel.add(label,BorderLayout.CENTER);
	    
	    button2=new JButton("carregar imagem");
        button2.addActionListener(this);
        panel.add(button2,BorderLayout.SOUTH);
	}
	
	protected static ImageIcon createImageIcon(String path) {
		
	       java.net.URL imgURL = CapturarImagem.class.getResource(path);
	       
	       if (imgURL != null) {
	           return new ImageIcon(imgURL);
	       } else {
	           System.err.println("Não foi possível encontrar o arquivo: " + path);
	           return null;
	       }
	 }
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		if (e.getSource() == button2){
        	
            chooser.showOpenDialog(null);
            file = chooser.getSelectedFile();
            
	        try{
	        	 img=ImageIO.read(file);
                 ImageIcon icon = new ImageIcon(img);
                 label.setIcon(icon);
                 
                 Dimension imageSize = new Dimension(icon.getIconWidth(),icon.getIconHeight()); 
                 label.setPreferredSize(imageSize); 

                 label.revalidate();
                 label.repaint(); 
            
	        }catch(IOException e1) {
            	e1.printStackTrace();
            }
        }
	}
	
	public static void main(String[] args) {
		
		 new CapturarImagem();
	}
	
}
Criado 13 de junho de 2014
Ultima resposta 16 de jun. de 2014
Respostas 6
Participantes 1