GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

Sistema para redimensionar imagens . . . (Código-Fonte + JAR)


#1

Bom dia galera, venho através desta compartilhar um simples programa para redimensionamento de imagem que desenvolvi para fins acadêmicos . . .

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author WINDOWS
 */
public class Main extends javax.swing.JFrame {
    File arquivo;
    /**
     * Creates new form flavio
     */
    public Main() throws IOException {
        initComponents();
    }
    /**
     * 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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        EXTENSAO_TEXTO = new javax.swing.JLabel();
        ALT = new javax.swing.JSlider();
        jLabel3 = new javax.swing.JLabel();
        LAR = new javax.swing.JSlider();
        LARGURA = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        EXTENSAO = new javax.swing.JComboBox();
        ALTURA1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("REDIMENSIONADOR DE IMAGENS");
        setResizable(false);
        getContentPane().setLayout(null);
        jTextField1.setEditable(false);
        jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jTextField1.setText("CLIQUE PARA SELECIONAR A IMAGEM");
        jTextField1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextField1MouseClicked(evt);
            }
        });
        jTextField1.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                jTextField1CaretUpdate(evt);
            }
        });
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });
        getContentPane().add(jTextField1);
        jTextField1.setBounds(10, 30, 245, 38);
        jLabel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        getContentPane().add(jLabel1);
        jLabel1.setBounds(270, 30, 240, 260);
        EXTENSAO_TEXTO.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        EXTENSAO_TEXTO.setText("EXTENSÃO - JPG");
        getContentPane().add(EXTENSAO_TEXTO);
        EXTENSAO_TEXTO.setBounds(10, 190, 240, 20);
        ALT.setMaximum(3000);
        ALT.setMinimum(1);
        ALT.setPaintTicks(true);
        ALT.setValue(768);
        ALT.setValueIsAdjusting(true);
        ALT.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                ALTMouseDragged(evt);
            }
        });
        getContentPane().add(ALT);
        ALT.setBounds(10, 100, 240, 40);
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("ARQUIVO");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(10, 10, 250, 20);
        LAR.setMaximum(3000);
        LAR.setMinimum(1);
        LAR.setPaintTicks(true);
        LAR.setValue(1024);
        LAR.setValueIsAdjusting(true);
        LAR.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                LARMouseDragged(evt);
            }
        });
        getContentPane().add(LAR);
        LAR.setBounds(10, 160, 240, 40);
        LARGURA.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        LARGURA.setText("LARGURA - 1024PX");
        getContentPane().add(LARGURA);
        LARGURA.setBounds(10, 140, 240, 20);
        jButton1.setText("SALVAR");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(10, 250, 240, 40);
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("VISUALIZADOR");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(270, 10, 240, 20);
        EXTENSAO.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "BMP", "JPG", "GIF", "PNG" }));
        EXTENSAO.setSelectedIndex(1);
        EXTENSAO.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EXTENSAOActionPerformed(evt);
            }
        });
        getContentPane().add(EXTENSAO);
        EXTENSAO.setBounds(10, 210, 240, 30);
        ALTURA1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        ALTURA1.setText("ALTURA - 768PX");
        getContentPane().add(ALTURA1);
        ALTURA1.setBounds(10, 80, 240, 20);
        jButton2.setText("SOBRE O SOFTWARE");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(10, 300, 500, 23);
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-530)/2, (screenSize.height-366)/2, 530, 366);
    }// </editor-fold>
    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
    }
    private void ALTMouseDragged(java.awt.event.MouseEvent evt) {
        EXTENSAO_TEXTO.setText("ALTURA - " + ALT.getValue() + "PX");
    }
    private void LARMouseDragged(java.awt.event.MouseEvent evt) {
        LARGURA.setText("LARGURA - " + LAR.getValue() + "PX");
    }
    private void jTextField1CaretUpdate(javax.swing.event.CaretEvent evt) {
    }
    private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) {
        JFileChooser jfc = new JFileChooser("C:/");
        int o = jfc.showOpenDialog(jfc);
        if (o == JFileChooser.APPROVE_OPTION) {
            arquivo = jfc.getSelectedFile();
            jTextField1.setText(arquivo.getName());
            visualizaImagem();
            int altura = 0, largura = 0;
            try {
                altura = ImageIO.read(arquivo).getHeight();
                largura = ImageIO.read(arquivo).getWidth();
            } catch (IOException ex) {
                System.out.println(ex);
            }
            ALT.setValue(altura);
            LAR.setValue(largura);
            EXTENSAO_TEXTO.setText("ALTURA - " + ALT.getValue() + "PX");
            LARGURA.setText("LARGURA - " + LAR.getValue() + "PX");
        }
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        salvaImagemRedimensionada();
    }
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
    private void EXTENSAOActionPerformed(java.awt.event.ActionEvent evt) {
EXTENSAO_TEXTO.setText("EXTENSÃO - "+EXTENSAO.getSelectedItem().toString());
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, "ESTE SOFTWARE FOI DESENVOLVIDO POR FLÁVIO SOUZA FINS ACADÊMICOS . . ."
        + "\nCONTATOS - flaviomirandadesouza@gmail.com / (85) 8794-3937".toUpperCase(),"SOBRE O SOFTWARE",JOptionPane.INFORMATION_MESSAGE);
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Main().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JSlider ALT;
    private javax.swing.JLabel ALTURA1;
    private javax.swing.JComboBox EXTENSAO;
    private javax.swing.JLabel EXTENSAO_TEXTO;
    private javax.swing.JSlider LAR;
    private javax.swing.JLabel LARGURA;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
    public void visualizaImagem() {
        Image i = null;
        try {
            File f = arquivo;
            i = ImageIO.read(f);
            jLabel1.setIcon(new ImageIcon(i.getScaledInstance(jLabel1.getWidth(), jLabel1.getHeight(), Image.SCALE_DEFAULT)));
        } catch (Exception ex) {
            if(ex.getMessage()==null){
                JOptionPane.showMessageDialog(null, "EXTENSÃO \""+arquivo.getName().substring(arquivo.getName().length()-4)
                        +"\" NÃO PERMITIDA\nFAVOR SELECIONAR UM ARQUIVO DE IMAGEM!!!\n\".bmp\",\".jpg\",\".png\",\".gif\"...","ATENÇÃO, VOCÊ NÃO SELECIONOU UMA IMAGEM!",JOptionPane.ERROR_MESSAGE);
                jTextField1.setText("CLIQUE PARA SELECIONAR A IMAGEM");
            }
        }
    }
    public void salvaImagemRedimensionada() {
        Image i = null;
        try {
            i = ImageIO.read(arquivo);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
        BufferedImage bf = new BufferedImage(LAR.getValue(), ALT.getValue(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bf.createGraphics();
        g2d.drawImage(i, 0, 0, LAR.getValue(), ALT.getValue(), null);
        try {
            ImageIO.write(bf, 
                    EXTENSAO.getSelectedItem().toString().toLowerCase(), 
                    new File(arquivo.getParent() + "/" + arquivo.getName().substring(0, arquivo.getName().length() - 4) + "_REDIMENSIONADA_" + LAR.getValue() + "PX_" + ALT.getValue() + "PX."+EXTENSAO.getSelectedItem().toString().toLowerCase()));
            jTextField1.setText("CLIQUE PARA SELECIONAR A IMAGEM");
            jLabel1.setIcon(null);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

vlw galera, qualquer dúvida sobre o código podem perguntar . . .


#2

DESCULPEM A DUPLICIDADE DO TÓPICO, QUANDO FUI ADICIONAR DEU UM ERRO NA PÁGINA ENTÃO PENSEI QUE NÃO TIVESSE ADICIONADO O TÓPICO . . .

VLW GALERA . . .


#3