[RESOLVIDO]Redimensionar Imagem em um JPanel

13 respostas
P

Pessoal, eu peguei esse programinha para salvar uma imagem no banco HSQLDB…
Eu to fazendo um cadastro de Usuarios só que tem um problema…

Mais nem sempre a imagem é do tamanho do Jpanel dai ela fica maior e nao aparece por completa, ou as vezes ela fica menor…

Existe algum jeito de redimensiona-la…
Na verdade existir existe, mais eu nao faço ideia… Tem como algum me ajudar???

Estou enviando o codigo, se alguem quiser mexer ou dar alguma dica eu agradeço muiiitooo…

Forte abraço e fica com Deus!!!

Codigo abaixo…

package swing;

import db.ConexaoDB;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;

public class frmImagem extends javax.swing.JFrame {

    private File arquivo = null;
    private static Connection conexao = null;
    private static String sql = null;

    public frmImagem() {
        initComponents();
    }
   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        pPainel = new javax.swing.JPanel();
        lblImagem = new javax.swing.JLabel();
        btnAbrir = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnBuscar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        pPainel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lblImagem.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout pPainelLayout = new javax.swing.GroupLayout(pPainel);
        pPainel.setLayout(pPainelLayout);
        pPainelLayout.setHorizontalGroup(
            pPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pPainelLayout.createSequentialGroup()
                .addGap(118, 118, 118)
                .addComponent(lblImagem, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(78, Short.MAX_VALUE))
        );
        pPainelLayout.setVerticalGroup(
            pPainelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pPainelLayout.createSequentialGroup()
                .addGap(79, 79, 79)
                .addComponent(lblImagem, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(75, Short.MAX_VALUE))
        );

        btnAbrir.setFont(new java.awt.Font("Verdana", 0, 10));
        btnAbrir.setText("Abrir");
        btnAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAbrirActionPerformed(evt);
            }
        });

        btnSalvar.setFont(new java.awt.Font("Verdana", 0, 10));
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnBuscar.setFont(new java.awt.Font("Verdana", 0, 10));
        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(201, 201, 201)
                        .addComponent(btnAbrir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnSalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBuscar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pPainel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pPainel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAbrir)
                    .addComponent(btnSalvar)
                    .addComponent(btnBuscar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btnAbrirActionPerformed(java.awt.event.ActionEvent evt) {                                         
         try {
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.showOpenDialog(this);

            arquivo = jFileChooser.getSelectedFile();

            if (arquivo != null) {
                String caminho = arquivo.getAbsolutePath();
                Image i = ImageIO.read(new File(caminho));

               ImageIcon imagem = new ImageIcon(i);
               lblImagem.setIcon(imagem);
               this.repaint();
            }

        } catch (IOException ex) {
            Logger.getLogger(frmImagem.class.getName()).log(Level.SEVERE, null, ex);
        }
}                                        

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {                                          

        if (arquivo != null) {
            PreparedStatement stmt = null;

            try {

                byte[] imageDataByteArray = new byte[(int) arquivo.length()];
                InputStream is = new FileInputStream(arquivo);
                is.read(imageDataByteArray);
                is.close();

                conexao = ConexaoDB.getInstance().getConnection();
                sql = "INSERT INTO imagens(codigo, imagem) VALUES (?, ?)";

                stmt = conexao.prepareStatement(sql);

                stmt.setInt(1, 9);
                stmt.setBytes(2, imageDataByteArray);

                stmt.execute();

            } catch (SQLException ex) {
                System.err.println("Erro sw: " + ex.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    stmt.close();
                    conexao.close();
                    ConexaoDB.closeConnection();
                } catch (SQLException ex) {
                    System.err.println("Erro sw1: " + ex.getMessage());
                }
            }
        }

    }                                         

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try{
            conexao = ConexaoDB.getInstance().getConnection();
            sql = "SELECT codigo, imagem FROM imagens WHERE codigo = ?";

            PreparedStatement stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, 3);

            ResultSet rs = stmt.executeQuery();
            if (rs.next()){
                byte[] imageDataByteArray = rs.getBytes("imagem");
                ImageIcon imagem = new ImageIcon(imageDataByteArray);
                lblImagem.setIcon(imagem);
                this.repaint();
            }

        }catch(Exception e){
            e.printStackTrace();
        }

    }                                         

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmImagem().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnAbrir;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JLabel lblImagem;
    private javax.swing.JPanel pPainel;
    // End of variables declaration                   

}

13 Respostas

V

Use o JImagePanel do projeto Towel:

P

Como que eu vou usar essa JImagePanel ??

V

Eis um tutorial:

P

nao ta dando certo

V

Sem que você diga o que não tá dando certo, que mensagem o seu IDE dá, ou poste o código modificado para usar a classe, fica muito difícil te ajudar.
Infelizmente esqueci a bola de cristal em casa hoje.

P

Nao da certo nada…
Mais se vc nao quer ajudar, nao precisar ser ignorante…

Concerteza deve ter pessoas que mandam bem aqui no Forum que sejam mais educadas…
Se eu estou falando que nao estou conseguindo, é porq nao estou conseguindo…

Nao seja um “Dr. House”…

Obs.: Eu nao consegui entender aquele tutorial…

V

Ignorante? Só te pedi mais informações.

Você tem que lembrar que não temos idéia do que você já escreveu nos seus fontes, de que não sabemos como você configurou o projeto na sua IDE (no caso, nem qual IDE você usa), que não temos a menor noção do quanto você entende de Java e que não podemos visualizar o que acontece no computador da sua casa.

Só o que temos aqui é você dizendo um problema e falando que a solução “não dá certo.” Isso não é muito esclarecedor, não concorda?

Um usuário utilizou essa classe há poucos dias no fórum:
http://www.guj.com.br/java/249369-nao-consigo-colocar-imagem-em-jframe#1294920

Você chegou incluir o projeto towel em seu projeto? Ou sequer copiar a classe do JImagePanel?

P

Entaum, é o seguinte…
Eu sou novo em JAVA…
USO a IDE Netbeans eu gostaria que ela ficasse redimensionada ou ajustada no JPanel…

Tipo, aquela classe JImagePanel é só dar um import???

Eu to usando aquele codigo que eu coloquei lá em cima…

assim que eu jogo em meu JPanel >>>

Para Abrir

try {
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.showOpenDialog(this);

            arquivo = jFileChooser.getSelectedFile();

            if (arquivo != null) {
                String caminho = arquivo.getAbsolutePath();
                Image i = ImageIO.read(new File(caminho));

                ImageIcon imagem = new ImageIcon(i);
                lblImagem.setIcon(imagem);
                this.repaint();
            }

...

Para Salvar

if (arquivo != null) {
            PreparedStatement stmt = null;

            try {

                byte[] imageDataByteArray = new byte[(int) arquivo.length()];
                InputStream is = new FileInputStream(arquivo);
                is.read(imageDataByteArray);
                is.close();

                conexao = ConexaoDB.getInstance().getConnection();
                sql = "INSERT INTO imagens(codigo, imagem) VALUES (?, ?)";

                stmt = conexao.prepareStatement(sql);

                stmt.setInt(1, 1);
                stmt.setBytes(2, imageDataByteArray);

                stmt.execute();

...

Desculpe, mais é que eu estou nervoso, pois tenho q fazer esse trabalho e só falta isso…

Na verdade eu to construindo um programa de cadastro de usuarios, e os professores exigiram que tenham a foto, só falta isso… Eu consegui, na verdade peguei em um tutorial como que salva, mais a cada foto como eu disse fica de tamanho diferente…
Será que com esses codigos tem como vc me ajudar agora???

Um abraço e mais uma vez me desculpe, é q to nervoso por naum conseguir…

V

A classe JImagePanel não faz parte do Java. Ela faz parte de um projeto separado, chamado Towel.

A forma mais fácil de usa-la, já que você parece bem iniciante, é fora do projeto Towel. Simplesmente copie o código que te passei ali em cima, crie uma classe JImagePanel no seu projeto e cole o código sobre ela. O Netbeans deve reclamar do nome do pacote, mas isso é só você corrigir.

Só em seguida você poderá usar a classe no seu projeto.

P

Amigao, o NetBeans nao corrigiu tudo nao…

Ele pedi para criar mais classes. Apagar algumas linhas…

O que eu faço???

EU copiei esse codigo aqui>>>

package com.towel.swing.img;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import com.towel.img.LoopImage;

/**
 * A panel that contains a background image. The background image is
 * automatically sized to fit in the panel.
 * 
 * @author Vinicius Godoy
 */
public class JImagePanel extends JPanel {
	private LoopImage images;
	// private BufferedImage image = null;
	private FillType fillType = FillType.RESIZE;

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 */
	public JImagePanel(BufferedImage img) {
		// setImage(img);
		images = new LoopImage(0, img);
	}

	/**
	 * Creates a new panel with the given background images looping at each tick
	 * interval.
	 * 
	 * @param tick
	 *            the time between swap the image
	 * @param imgs
	 *            The background images.
	 */
	public JImagePanel(long tick, BufferedImage... imgs) {
		images = new LoopImage(tick, imgs);
		new Looper().start();
	}

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 * @throws IOException
	 *             , if the image file is not found.
	 */
	public JImagePanel(File imgSrc) throws IOException {
		this(ImageIO.read(imgSrc));
	}

	/**
	 * Default constructor, should be used only for sub-classes
	 */
	protected JImagePanel() {

	}

	/**
	 * Creates a new panel with the given background image.
	 * 
	 * @param img
	 *            The background image.
	 * @throws IOException
	 *             , if the image file is not found.
	 */
	public JImagePanel(String fileName) throws IOException {
		this(new File(fileName));
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 */
	public final void setImage(BufferedImage img) {
		if (img == null)
			throw new NullPointerException("Buffered image cannot be null!");

		this.images = new LoopImage(0, img);
		// this.image = img;
		invalidate();
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 * @throws IOException
	 *             If the file does not exist or is invalid.
	 */
	public void setImage(File img) throws IOException {
		setImage(ImageIO.read(img));
	}

	/**
	 * Changes the image panel image.
	 * 
	 * @param img
	 *            The new image to set.
	 * @throws IOException
	 *             If the file does not exist or is invalid.
	 */
	public void setImage(String fileName) throws IOException {
		setImage(new File(fileName));
	}

	/**
	 * Returns the image associated with this image panel.
	 * 
	 * @return The associated image.
	 */
	public BufferedImage getImage() {
		return images.getCurrent();
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g.create();
		fillType.drawImage(this, g2d, images.getCurrent());
		g2d.dispose();
	}

	/**
	 * Returns the way this image fills itself.
	 * 
	 * @return The fill type.
	 */
	public FillType getFillType() {
		return fillType;
	}

	/**
	 * Changes the fill type.
	 * 
	 * @param fillType
	 *            The new fill type
	 * @throws IllegalArgumentException
	 *             If the fill type is null.
	 */
	public void setFillType(FillType fillType) {
		if (fillType == null)
			throw new IllegalArgumentException("Invalid fill type!");

		this.fillType = fillType;
		invalidate();
	}

	public static enum FillType {
		/**
		 * Make the image size equal to the panel size, by resizing it.
		 */
		RESIZE {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				g2d.drawImage(image, 0, 0, panel.getWidth(), panel.getHeight(),
						null);
			}
		},

		/**
		 * Centers the image on the panel.
		 */
		CENTER {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				int left = (panel.getWidth() - image.getWidth()) / 2;
				int top = (panel.getHeight() - image.getHeight()) / 2;
				g2d.drawImage(image, left, top, null);
			}

		},
		/**
		 * Makes several copies of the image in the panel, putting them side by
		 * side.
		 */
		SIDE_BY_SIDE {
			@Override
			public void drawImage(JPanel panel, Graphics2D g2d,
					BufferedImage image) {
				Paint p = new TexturePaint(image, new Rectangle2D.Float(0, 0,
						image.getWidth(), image.getHeight()));
				g2d.setPaint(p);
				g2d.fillRect(0, 0, panel.getWidth(), panel.getHeight());
			}
		};

		public abstract void drawImage(JPanel panel, Graphics2D g2d,
				BufferedImage image);
	}

	private class Looper extends Thread {
		public Looper() {
			setDaemon(true);
		}

		public void run() {
			while (true) {
				repaint();
				try {
					sleep(images.tick);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
P

Eu consegui arrumar os erros aqui amigao… (Eu Acho)…

Me da umas dicas de como eu faço para redimensionar a imagem agora usando essa classe que vc me passou…

Fico no aguardo…

Abraços!!!

V

Essa classe é um painel, igual ao JPanel, mas com uma imagem no fundo.
Por padrão, ele já redimensiona a imagem para o tamanho do painel.

Agora que você já conseguiu colocar um JImagePanel num projeto, tente seguir o tutorial do Mark que te passei.

P

Blz irmaozao…
Eu vou tentar aqui…
Assim que eu conseguir ou ter alguma dificuldade eu te comunico. Pode ser???

Criado 10 de agosto de 2011
Ultima resposta 11 de ago. de 2011
Respostas 13
Participantes 2