Carregar Imagem

4 respostas
C

Bom dia a todos.

Estou fazendo um projeto com integrado co mo Flex

Mas acho q meu problema esta no java

bom a ideia é essa:

Eu procuro um uma imagem, e adciono ela, só que eu queria visualizar a imagem antes de salvar no banco.

No meu caso ele ja esta add direto no bacno qndo eu salvo ao invez de exibir.

public void fazerUploadCranioCaudal(byte[] bytes, String fileName) throws Exception 
{       
	
			
	fileName = "c:\\imagens_projeto\\" +  fileName;
	System.out.println(fileName);
	File arquivo = new File(fileName);        
	FileOutputStream fos = new FileOutputStream(arquivo);        
	fos.write(bytes);        
	fos.close();    
	}
public void fazerUploadMedioLateral(byte[] bytes, String fileName) throws Exception 
{       
	
			
	fileName = "c:\\imagens_projeto\\" +  fileName;
	System.out.println(fileName);
	File arquivo = new File(fileName);        
	FileOutputStream fos = new FileOutputStream(arquivo);        
	fos.write(bytes);        
	fos.close();    
	}
public void fazerUploadCaudalForcada(byte[] bytes, String fileName) throws Exception 
{       
	
			
	fileName = "c:\\imagens_projeto\\" +  fileName;
	System.out.println(fileName);
	File arquivo = new File(fileName);        
	FileOutputStream fos = new FileOutputStream(arquivo);        
	fos.write(bytes);        
	fos.close();    
	}

public void fazerUploadCleavage(byte[] bytes, String fileName) throws Exception 
{       
	
			
	fileName = "c:\\imagens_projeto\\" +  fileName;
	System.out.println(fileName);
	File arquivo = new File(fileName);        
	FileOutputStream fos = new FileOutputStream(arquivo);        
	fos.write(bytes);        
	fos.close();    
	}


public void fazerUploadPerfil(byte[] bytes, String fileName) throws Exception 
{       
	
			
	fileName = "c:\\imagens_projeto\\" +  fileName;
	System.out.println(fileName);
	File arquivo = new File(fileName);        
	FileOutputStream fos = new FileOutputStream(arquivo);        
	fos.write(bytes);        
	fos.close();    
	}

E aqui segue a parte do FLEX que faz o tratamento…EU gostaria de fazer a exibição da imagem antes de salva-la no banco

// ActionScript file
		 import mx.controls.Alert;
	     import mx.rpc.AsyncToken;            
	     import mx.rpc.events.FaultEvent;            
	     import mx.rpc.events.ResultEvent;            

	     private var refUploadFile:FileReference;         
	        /**             * @private             * Chamado quando o botão de adicionar arquivo for clicado.             */    
	     private function adicionarArquivos():void 
{               
	     	 /* Inicializa o FileReference a adicinar os Listeners */
	     	 refUploadFile = new FileReference();                
	     	 refUploadFile.browse();                
	     	 refUploadFile.addEventListener(Event.SELECT, trateArquivoSelecionado);                
	     	 refUploadFile.addEventListener(Event.COMPLETE, trateArquivoCompleto);            
}            /**             * @private             * Chamado quando o usuário selecionar o arquivo na pop up.             */            
	     	




 		private function adicionarArquivos2():void 
			{               
	     	 /* Inicializa o FileReference a adicinar os Listeners */
	     	 refUploadFile = new FileReference();                
	     	 refUploadFile.browse();                
	     	 refUploadFile.addEventListener(Event.SELECT, trateArquivoSelecionado2);                
	     	 refUploadFile.addEventListener(Event.COMPLETE, trateArquivoCompleto2);            
			}            /**             * @private             * Chamado quando o usuário selecionar o arquivo na pop up.             */            
	     	
	     	
	     	
	     	 private function adicionarArquivos3():void 
{               
	     	 /* Inicializa o FileReference a adicinar os Listeners */
	     	 refUploadFile = new FileReference();                
	     	 refUploadFile.browse();                
	     	 refUploadFile.addEventListener(Event.SELECT, trateArquivoSelecionado3);                
	     	 refUploadFile.addEventListener(Event.COMPLETE, trateArquivoCompleto3);            
}            /**             * @private             * Chamado quando o usuário selecionar o arquivo na pop up.             */            
	     	
	     	 private function adicionarArquivos4():void 
{               
	     	 /* Inicializa o FileReference a adicinar os Listeners */
	     	 refUploadFile = new FileReference();                
	     	 refUploadFile.browse();                
	     	 refUploadFile.addEventListener(Event.SELECT, trateArquivoSelecionado4);                
	     	 refUploadFile.addEventListener(Event.COMPLETE, trateArquivoCompleto4);            
}            /**             * @private             * Chamado quando o usuário selecionar o arquivo na pop up.             */            
	     	
	     	
	     	 private function adicionarArquivos5():void 
{               
	     	 /* Inicializa o FileReference a adicinar os Listeners */
	     	 refUploadFile = new FileReference();                
	     	 refUploadFile.browse();                
	     	 refUploadFile.addEventListener(Event.SELECT, trateArquivoSelecionado5);                
	     	 refUploadFile.addEventListener(Event.COMPLETE, trateArquivoCompleto5);            
}            /**             * @private             * Chamado quando o usuário selecionar o arquivo na pop up.             */            
	     	

 
	     	private function trateArquivoSelecionado(event:Event):void 
	     	 {                /* Este metodo LOAD, foi implementado na versao do FP 10,                
							   * é graças a ele que conseguimos recuperar o ByteArray e enviar para o Server */                
	     	  		refUploadFile.load();            
	     	  }          
	     	  
	     	   
	     	   
	     	   private function trateArquivoSelecionado2(event:Event):void 
	     	 {                /* Este metodo LOAD, foi implementado na versao do FP 10,                
							   * é graças a ele que conseguimos recuperar o ByteArray e enviar para o Server */                
	     	  		refUploadFile.load();            
	     	  }   
	     	  
	     	  
	     	  
	     	   private function trateArquivoSelecionado3(event:Event):void 
	     	 {                /* Este metodo LOAD, foi implementado na versao do FP 10,                
							   * é graças a ele que conseguimos recuperar o ByteArray e enviar para o Server */                
	     	  		refUploadFile.load();            
	     	  } 
	     	  
	     	  
	     	   private function trateArquivoSelecionado4(event:Event):void 
	     	 {                /* Este metodo LOAD, foi implementado na versao do FP 10,                
							   * é graças a ele que conseguimos recuperar o ByteArray e enviar para o Server */                
	     	  		refUploadFile.load();            
	     	  }     
 /**             * @private             * Chamado quando o usuario selecinar o arquivo na popup.    
	     	  *          */           
	     
	       private function trateArquivoSelecionado5(event:Event):void 
	     	 {                /* Este metodo LOAD, foi implementado na versao do FP 10,                
							   * é graças a ele que conseguimos recuperar o ByteArray e enviar para o Server */                
	     	  		refUploadFile.load();            
	     	  }     
			
			
			
			
			private function trateArquivoCompleto(event:Event):void 
	     { 
	               /* Pega a referencia do FileReference */ 
	              refUploadFile = event.currentTarget as FileReference;
          		   /* Variavel para armazenar o ByteArray */    
	              var data:ByteArray = new ByteArray();
  				   /* readBytes é responsavel por ler logicamente os dados do FileReference        
				    * e repassar o valor do ByteArray do arquivo para a variavel armazenadora 'DATA' */               
	                refUploadFile.data.readBytes(data, 0, refUploadFile.data.length);
	                Controlador.fazerUploadCranioCaudal(data, refUploadFile.name); 
	       }
	       
	       private function trateArquivoCompleto2(event:Event):void 
	     { 
	               /* Pega a referencia do FileReference */ 
	              refUploadFile = event.currentTarget as FileReference; 
	            
          /* Variavel para armazenar o ByteArray */    
	              var data:ByteArray = new ByteArray();
  /* readBytes é responsavel por ler logicamente os dados do FileReference        
* e repassar o valor do ByteArray do arquivo para a variavel armazenadora 'DATA' */               
	                refUploadFile.data.readBytes(data, 0, refUploadFile.data.length);
	                Controlador.fazerUploadMedioLateral(data, refUploadFile.name);  
	     }


			
			
			private function trateArquivoCompleto3(event:Event):void 
	     { 
	               /* Pega a referencia do FileReference */ 
	              refUploadFile = event.currentTarget as FileReference;
          		   /* Variavel para armazenar o ByteArray */    
	              var data:ByteArray = new ByteArray();
  				   /* readBytes é responsavel por ler logicamente os dados do FileReference        
				    * e repassar o valor do ByteArray do arquivo para a variavel armazenadora 'DATA' */               
	                refUploadFile.data.readBytes(data, 0, refUploadFile.data.length);
	                Controlador.fazerUploadCaudalForcada(data, refUploadFile.name);

	     }
	     
	     	private function trateArquivoCompleto4(event:Event):void 
	     { 
	               /* Pega a referencia do FileReference */ 
	              refUploadFile = event.currentTarget as FileReference;
          		   /* Variavel para armazenar o ByteArray */    
	              var data:ByteArray = new ByteArray();
  				   /* readBytes é responsavel por ler logicamente os dados do FileReference        
				    * e repassar o valor do ByteArray do arquivo para a variavel armazenadora 'DATA' */               
	                refUploadFile.data.readBytes(data, 0, refUploadFile.data.length);
	                Controlador.fazerUploadCleavage(data, refUploadFile.name);

	     }
	     
	     private function trateArquivoCompleto5(event:Event):void 
	     { 
	               /* Pega a referencia do FileReference */ 
	              refUploadFile = event.currentTarget as FileReference;
          		   /* Variavel para armazenar o ByteArray */    
	              var data:ByteArray = new ByteArray();
  				   /* readBytes é responsavel por ler logicamente os dados do FileReference        
				    * e repassar o valor do ByteArray do arquivo para a variavel armazenadora 'DATA' */               
	                refUploadFile.data.readBytes(data, 0, refUploadFile.data.length);
	                Controlador.fazerUploadPerfil(data, refUploadFile.name);      

	     }
/**             * @private             * Exibe a mensagem ao usuario informando que o Upload foi realizado com sucesso.             */            
	      
				 private function uploadSucesso(event:ResultEvent):void 
	      {                
	             Alert.show("Arquivo salvo no server com sucesso", "Sucesso");
	             
	      }            
	      



/**             * @private             * Exibe a mensagem de erro do motivo do Upload não ter sido realizado com sucesso.             */   
	      private function uploadErro(event:FaultEvent):void 
	      {                
	               Alert.show(event.toString(), 'Erro');           
	        }

4 Respostas

I

Se a imagem está sendo corretamente inserida na base, como vc pode dizer que o problema é no java?
Não vejo um código seu tentando mostrar essa imagem num preview da vida(como dentro de um JLabel).

Na parte Flex infelizmente não posso lhe ajudar, não manjo patavinas. :frowning:

C

Tipo…teria como me dar uma luz de usando o previw no java?

depois eu me virava com o flex

I
Imagine que vc tem um JButton chamado inserirFoto que chama um JFileChooser de imagens.Dentro do ActionListener vc poderia fazer algo assim:
//**********Classe Ouvinte do botão inserirFoto****************************************
      inserirFoto.addActionListener(
           new ActionListener() {
              public void actionPerformed(ActionEvent evt) {               
               if (fc == null) {
                    fc = new JFileChooser();

               //Adiciona um filtro de arquivos próprio(Apenas Imagens) e desabilita  
               //o padrão (Aceitar Todos os arquivos) 
                fc.addChoosableFileFilter(new ImageFilter());
                fc.setAcceptAllFileFilterUsed(false);

               //Adiciona ícones padrão para diferentes tipos de arquivos(JPEG,GIF..).
                fc.setFileView(new ImageFileView());

               //Adiciona a janela de preview(visualização de imagem).
                fc.setAccessory(new ImagePreview(fc));
                       
                                                        }
                             
                 //Mostra o FileChooser.
                int returnVal = fc.showDialog(Cadastro.this,"Anexar"); 
                
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                     imagem=new ImageIcon(file.getPath());//pega o caminho da imagem
                        novaImagem=new ImageIcon(imagem.getImage().//pega a imagem com novo tam
                                          getScaledInstance(90, -1,
                                                      Image.SCALE_DEFAULT));
                      
                        atualizaLabel(novaImagem);
                        repaint();   //atualiza o JLabel com a img selecionada
                     
                    //implementar gravar no banco
                                        }            
                        
                  //Limpa o File Chooser para a próxima vez que for mostrado .
                fc.setSelectedFile(null);         
                        
                                                            }//fim do actionPerformed
              }
           );//fim da inner class do Listener
atualizaLabel seria um método assim:
private void atualizaLabel(ImageIcon icon){
   	    
   	    img.setIcon(icon);
   	         
        if (icon != null) {
            img.setText(null);
            
            //repaint();
        } else {
            img.setText("Imagem não disponível!");
        }
   	
   }
onde img é um JLabel. Agora vamos ao JFileChooser de imagens e suas classes acessórias:
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.File;

/* ImagePreview.java é um 1.4 exemplo usado pelo FileChooser dentro de sua classe que chama o FileChooser **/
public class ImagePreview extends JComponent
                          implements PropertyChangeListener {
    ImageIcon thumbnail = null;
    File file = null;

    public ImagePreview(JFileChooser fc) {
        setPreferredSize(new Dimension(100, 50));
        fc.addPropertyChangeListener(this);
    }

    public void loadImage() {
        if (file == null) {
            thumbnail = null;
            return;
        }

        //Don't use createImageIcon (which is a wrapper for getResource)
        //because the image we're trying to load is probably not one
        //of this program's own resources.
        ImageIcon tmpIcon = new ImageIcon(file.getPath());
        if (tmpIcon != null) {
            if (tmpIcon.getIconWidth() > 90) {
                thumbnail = new ImageIcon(tmpIcon.getImage().
                                          getScaledInstance(90, -1,
                                                      Image.SCALE_DEFAULT));
            } else { //sem necessidade de miniaturizar
                thumbnail = tmpIcon;
            }
        }
    }

    public void propertyChange(PropertyChangeEvent e) {
        boolean update = false;
        String prop = e.getPropertyName();

        //Se o diretório muda,não mostra a imagem.
        if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
            file = null;
            update = true;

        //Se um arquivo é seleciodado, find out which one.
        } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
            file = (File) e.getNewValue();
            update = true;
        }

        //Atualiza o preview correspondente.
        if (update) {
            thumbnail = null;
            if (isShowing()) {
                loadImage();
                repaint();
            }
        }
    }

    protected void paintComponent(Graphics g) {
        if (thumbnail == null) {
            loadImage();
        }
        if (thumbnail != null) {
            int x = getWidth()/2 - thumbnail.getIconWidth()/2;
            int y = getHeight()/2 - thumbnail.getIconHeight()/2;

            if (y < 0) {
                y = 0;
            }

            if (x < 5) {
                x = 5;
            }
            thumbnail.paintIcon(this, g, x, y);
        }
    }//fim do método paintComponent()
 }
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

/* ImageFilter.java is a 1.4 example */
public class ImageFilter extends FileFilter {

    //Accept all directories and all gif, jpg, tiff, or png files.
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }

        String extension = Utils.getExtension(f);
        if (extension != null) {
            if (extension.equals(Utils.tiff) ||
                extension.equals(Utils.tif) ||
                extension.equals(Utils.gif) ||
                extension.equals(Utils.jpeg) ||
                extension.equals(Utils.jpg) ||
                extension.equals(Utils.png)) {
                    return true;
            } else {
                return false;
            }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Apenas Imagens";
    }
}
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;

/* ImageFileView.java is a 1.4 example used pelo FileChooser  */
public class ImageFileView extends FileView {
    ImageIcon jpgIcon = Utils.createImageIcon("imagens/jpgIcon.gif");
    ImageIcon gifIcon = Utils.createImageIcon("imagens/gifIcon.gif");
    ImageIcon tiffIcon = Utils.createImageIcon("imagens/tiffIcon.gif");
    ImageIcon pngIcon = Utils.createImageIcon("imagens/pngIcon.png");

    public String getName(File f) {
        return null; //let the L&F FileView figure this out
    }

    public String getDescription(File f) {
        return null; //let the L&F FileView figure this out
    }

    public Boolean isTraversable(File f) {
        return null; //let the L&F FileView figure this out
    }

    public String getTypeDescription(File f) {
        String extension = Utils.getExtension(f);
        String type = null;

        if (extension != null) {
            if (extension.equals(Utils.jpeg) ||
                extension.equals(Utils.jpg)) {
                type = "JPEG Image";
            } else if (extension.equals(Utils.gif)){
                type = "GIF Image";
            } else if (extension.equals(Utils.tiff) ||
                       extension.equals(Utils.tif)) {
                type = "TIFF Image";
            } else if (extension.equals(Utils.png)){
                type = "PNG Image";
            }
        }
        return type;
    }

    public Icon getIcon(File f) {
        String extension = Utils.getExtension(f);
        Icon icon = null;

        if (extension != null) {
            if (extension.equals(Utils.jpeg) ||
                extension.equals(Utils.jpg)) {
                icon = jpgIcon;
            } else if (extension.equals(Utils.gif)) {
                icon = gifIcon;
            } else if (extension.equals(Utils.tiff) ||
                       extension.equals(Utils.tif)) {
                icon = tiffIcon;
            } else if (extension.equals(Utils.png)) {
                icon = pngIcon;
            }
        }
        return icon;
    }
}

Se não me engano, esses parte desse código pertence ao FileChooserDemo2.java do tutorial de swing da Sun(ok, Oracle).Vc pode dar uma boa olhada lá. :wink:

C

Krai…Nao pensei nisso

na vdd eu estava pensnado em criar um popup parar abrir a imagem em uma nova “label” com a opção de salvar nela

ahuahuauha

boa gostei dessa vou testar ak…apesar que depois vou ter q passar para o flex

Viu, se for do seu poder, veja se existe ClovisCMB ainda, eu perdi a senha de acesso, e meu email novo é [email removido]

faz muito tempo q sou membro do guj, dai fiquei um tempo fora perdi o antigo email

=/

Criado 2 de outubro de 2010
Ultima resposta 2 de out. de 2010
Respostas 4
Participantes 2