Salvar uma imagem

4 respostas
A

alguem sabe qual´o componente q se usa para carregar e como salvar uma imagem…tipo meu sistema tem um cadastro de funcionário e nesse cadastro tenho de gravar a foto do funcionario…mas naum tenho nem idéia de como carrega e salva essa imagem…

vcs podem me ajudar…

4 Respostas

furutani

Primeiro seu sistema é web?
Se sim procure por algum componente de upload
Se não use o JFileChooser

Segundo você que salvar isso onde?
No banco, em um diretório remoto?

A

é um sistema desktop…e eu quero salvar na memoria…

renzonuccitelli

Há um tempo eu precise mostrar a foto, em escala adequada e salvar. Procurei e adaptei o seguinte código:

public class PainelFotografico extends JPanel {
	private File foto=null;
	private ByteArrayOutputStream fotoComTamanhoIdeal=null;
	private JLabel labelFoto;
	private JInternalFrame frame;
	private final int ALTURA_MAX=480;
	private final int LARGURA_MAX=600;
	private JFileChooser fileC=null;
	
	protected File getFoto() {
		return foto;
	}
	
	protected JInternalFrame getFrame(){
		return this.frame;
	}

	protected PainelFotografico(JInternalFrame frame){
		super();
		this.frame=frame;
		configurar();
	}
	
	private void configurar(){
		ActionProcurarFoto actionProcurarFoto=new ActionProcurarFoto(this){
			public void execute(){
				if(fileC==null){
				fileC=new JFileChooser();
				fileC.setMultiSelectionEnabled(false);
				fileC.setDialogTitle("Foto do produto");
				fileC.setFileFilter(new FileNameExtensionFilter("JPG","jpg"));
				fileC.setFileSelectionMode(JFileChooser.FILES_ONLY);
				}
				fileC.showOpenDialog(null);
				if(fileC.getSelectedFile().isFile()){
					this.getPainelFotografico().setImagem(fileC.getSelectedFile().getAbsolutePath());
				}
				this.exibirPosicaoOtima();
				
				
			}
		};
		JActButton botaoProcurarFoto=new JActButton("Inserir Foto",actionProcurarFoto);
		this.add(botaoProcurarFoto);
		this.labelFoto=new JLabel("Sem foto para mostrar");
		this.add(this.labelFoto);
	}
	
	protected void setImagem(String path){
		if(path!=null){
			ImageIcon img=new ImageIcon(createThumbnail(new ImageIcon(path)).toByteArray());
			this.foto=new File(path);
			setImagem(img);
		}
		else{
			this.labelFoto.setIcon(null);
			this.labelFoto.setText("Sem foto para mostrar");
		}
	}
	
	
	
	private void setImagem(ImageIcon img){
		this.labelFoto.setText(null);
		this.labelFoto.setIcon(img);
		this.labelFoto.setSize(img.getIconWidth(),img.getIconHeight());
		this.labelFoto.setVisible(true);
		this.frame.setSize(getMaior(this.labelFoto.getWidth(),(int) this.frame.getPreferredSize().getWidth())
				,(int)(this.frame.getPreferredSize().getHeight()+this.labelFoto.getHeight()));
		
	}
	
	private int getMaior(int altura1, int altura2){
		if(altura1>altura2)
			return altura1;
		return altura2;
	}
	
	private double getScale(int width,int height){
		double scale=(double) LARGURA_MAX/(double)width;
		if(scale>(double) ALTURA_MAX/(double)height)
			scale= (double) ALTURA_MAX/(double)height;
		if(scale>=1)
			return 1;
		return scale;
			
	}
	
	
	

		   
	private ByteArrayOutputStream createThumbnail(ImageIcon icone) {  
		ByteArrayOutputStream btImage = new ByteArrayOutputStream();  
		try {  
			// Get the image from a file.  
			Image inImage = icone.getImage();  
			// Determine the scale.  
			double scale = getScale(icone.getIconWidth(),icone.getIconHeight());   
			int scaledW = (int)(scale*(double)icone.getIconWidth());  
			int scaledH = (int)(scale*(double)icone.getIconHeight());  

			// Create an image buffer in  
			//which to paint on.  
			BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);  

			// Set the scale.  
			AffineTransform tx = new AffineTransform();  

			// If the image is smaller than  
			//the desired image size,  
			// don't bother scaling.  
			if (scale < 1.0d){  
				                 tx.scale(scale, scale);  
            } 
			  

			// Paint image.  
			Graphics2D g2d = outImage.createGraphics();  
			g2d.drawImage(inImage, tx, null);  
			g2d.dispose();  

			// JPEG-encode the image  
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(btImage);  
			encoder.encode(outImage);  

			btImage.close();
			this.fotoComTamanhoIdeal=btImage;

		} catch(IOException e){  
			e.printStackTrace();  
		}  
		return btImage;  
	}

	protected ByteArrayOutputStream getFotoComTamanhoIdeal() {
		return fotoComTamanhoIdeal;
	}
	
}

Pra gravar, basta usar o getFotoComTamanhoIdeal e salvar o array de bytes onde vc kiser...

renzonuccitelli

Ah, essa classe ta precisando de uma refatorada, faz muito tempo que eu fiz e foi só pra diversão. Além disso, eu estava usando o SwingBean, entao troque o JActButton por um botao normao e na acao do botao coloque um ActionListener…

Criado 4 de dezembro de 2008
Ultima resposta 4 de dez. de 2008
Respostas 4
Participantes 3