Método que recebe Array de byte e retorna o mesmo redimensionado

2 respostas
rafadelnero

Bom dia, já procurei em diversos lugares no fórum e no google como eu faria esse tratamente e achei diversos tópicos, mas não era exatamente o que eu preciso, peguei trechos de códigos, e estava funcionando, preciso saber se está correto meu método, deve ser detalhe simples:

Método:

private byte[] redimensionaImagem(byte[] arquivoImagem) throws IOException {
		BufferedImage img = ImageIO
				.read(new ByteArrayInputStream(arquivoImagem));

		BufferedImage novaImagem = new BufferedImage(120, 120, img.getType());

		Graphics2D g2d = novaImagem.createGraphics();
		g2d.drawImage(novaImagem, 0, 0, 120, 120, null);
		g2d.dispose();

		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			ImageIO.write(novaImagem, "JPG", byteArrayOutputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return byteArrayOutputStream.toByteArray();
	}

Desde já agradeço!

2 Respostas

Marcelo_SCS

Veja isso:

http://www.mkyong.com/java/how-to-resize-an-image-in-java/

Att.

E
package guj;

import java.awt.AlphaComposite;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

class RedimensionarImagem {

    public static String formato(String nomeArquivo) {
        nomeArquivo = nomeArquivo.trim().toLowerCase();
        if (nomeArquivo.endsWith(".jpg"))
            return "JPEG";
        else if (nomeArquivo.endsWith(".png"))
            return "PNG";
        else if (nomeArquivo.endsWith(".gif"))
            return "GIF";
        else
            return "PNG"; // formato padrão
    }

    public static void redimensionar(String entrada, String saida, String formato, double porcentagem) throws IOException {
        BufferedImage inputImg = ImageIO.read(new File(entrada));
        int oldWidth = inputImg.getWidth();
        int oldHeight = inputImg.getHeight();
        int newWidth = (int) Math.round(oldWidth * porcentagem / 100);
        int newHeight = (int) Math.round(oldHeight * porcentagem / 100);
        int type = inputImg.getType();
        BufferedImage outputImg = new BufferedImage(newWidth, newHeight, type);
        Graphics2D g = outputImg.createGraphics();
        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(inputImg, 0, 0, newWidth, newHeight, null);
        ImageIO.write(outputImg, formato, new File(saida));
        g.dispose();
    }
}

public class RedimensionarImagemFrame extends JFrame {
    private JPanel pnlInput;
    private JTextField txtInputFile;
    private JButton btnInput;
    private JPanel pnlOutput;
    private JTextField txtOutputFile;
    private JButton btnOutput;
    private JPanel pnlSpinner;
    private JSpinner spnZoom;
    private JButton btnProcessar;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    RedimensionarImagemFrame frame = new RedimensionarImagemFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public RedimensionarImagemFrame() {
        setTitle("Redimensionar Imagem");
        setBounds(100, 100, 450, 301);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new MigLayout("", "[grow]", "[grow][grow][grow][][][]"));
        getContentPane().add(getPnlInput(), "cell 0 0,grow");
        getContentPane().add(getPnlOutput(), "cell 0 1,grow");
        getContentPane().add(getPnlSpinner(), "flowy,cell 0 2,grow");
        getContentPane().add(getBtnProcessar(), "cell 0 3,alignx center");

    }

    private JPanel getPnlInput() {
        if (pnlInput == null) {
            pnlInput = new JPanel();
            pnlInput.setBorder(new TitledBorder(null, "Imagem de entrada", TitledBorder.LEADING, TitledBorder.TOP, null, null));
            pnlInput.setLayout(new MigLayout("", "[grow][]", "[]"));
            pnlInput.add(getTxtInputFile(), "cell 0 0,growx");
            pnlInput.add(getBtnInput(), "cell 1 0");
        }
        return pnlInput;
    }

    private JTextField getTxtInputFile() {
        if (txtInputFile == null) {
            txtInputFile = new JTextField();
            txtInputFile.setColumns(10);
        }
        return txtInputFile;
    }

    private JButton getBtnInput() {
        if (btnInput == null) {
            btnInput = new JButton("...");
            btnInput.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser jfc = new JFileChooser();
                    jfc.setDialogTitle("Imagem de entrada");
                    jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                    jfc.setFileFilter(new FileNameExtensionFilter("Arquivos de Imagem", "jpg", "png", "gif"));
                    int option = jfc.showOpenDialog(RedimensionarImagemFrame.this);
                    if (option == JFileChooser.APPROVE_OPTION && !jfc.getSelectedFile().isDirectory()) {
                        txtInputFile.setText(jfc.getSelectedFile().getAbsolutePath());
                    }
                }
            });
        }
        return btnInput;
    }

    private JPanel getPnlOutput() {
        if (pnlOutput == null) {
            pnlOutput = new JPanel();
            pnlOutput.setBorder(new TitledBorder(null, "Imagem de Sa\u00EDda", TitledBorder.LEADING, TitledBorder.TOP, null, null));
            pnlOutput.setLayout(new MigLayout("", "[grow][]", "[]"));
            pnlOutput.add(getTxtOutputFile(), "cell 0 0,growx");
            pnlOutput.add(getBtnOutput(), "cell 1 0");
        }
        return pnlOutput;
    }

    private JTextField getTxtOutputFile() {
        if (txtOutputFile == null) {
            txtOutputFile = new JTextField();
            txtOutputFile.setColumns(10);
        }
        return txtOutputFile;
    }

    private JButton getBtnOutput() {
        if (btnOutput == null) {
            btnOutput = new JButton("...");
            btnOutput.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser jfc = new JFileChooser();
                    jfc.setDialogTitle("Imagem de Saida");
                    jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                    jfc.setFileFilter(new FileNameExtensionFilter("Arquivos de Imagem", "jpg", "png", "gif"));
                    int option = jfc.showSaveDialog(RedimensionarImagemFrame.this);
                    if (option == JFileChooser.APPROVE_OPTION && !jfc.getSelectedFile().isDirectory()) {
                        txtOutputFile.setText(jfc.getSelectedFile().getAbsolutePath());
                    }
                }
            });
        }
        return btnOutput;
    }

    private JPanel getPnlSpinner() {
        if (pnlSpinner == null) {
            pnlSpinner = new JPanel();
            pnlSpinner.setBorder(new TitledBorder(null, "Porcentagem de Amplia\u00E7\u00E3o", TitledBorder.LEADING,
                    TitledBorder.TOP, null, null));
            pnlSpinner.setLayout(new MigLayout("", "[grow]", "[]"));
            pnlSpinner.add(getSpnZoom(), "cell 0 0,alignx right");
        }
        return pnlSpinner;
    }

    private JSpinner getSpnZoom() {
        if (spnZoom == null) {
            spnZoom = new JSpinner();
            spnZoom.setModel(new SpinnerNumberModel(100, 1, 1000000, 1));
        }
        return spnZoom;
    }

    private JButton getBtnProcessar() {
        if (btnProcessar == null) {
            btnProcessar = new JButton("Processar!");
            btnProcessar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if (txtInputFile.getText().trim().isEmpty() || txtOutputFile.getText().trim().isEmpty())
                        return;
                    try {
                        RedimensionarImagem.redimensionar(txtInputFile.getText(), txtOutputFile.getText(),
                            RedimensionarImagem.formato(txtOutputFile.getText()), ((Number) spnZoom.getValue()).doubleValue());
                        JOptionPane.showMessageDialog(RedimensionarImagemFrame.this, String.format("%s convertido para %s",
                            txtInputFile.getText(), txtOutputFile.getText()), "Redimensionar Imagem", JOptionPane.OK_OPTION);
                    } catch (Exception ex) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        ex.printStackTrace(pw);
                        JOptionPane.showMessageDialog(RedimensionarImagemFrame.this, sw.toString(), "Erro:", JOptionPane.OK_OPTION
                            | JOptionPane.QUESTION_MESSAGE);
                    }
                }
            });
        }
        return btnProcessar;
    }
}
Criado 21 de dezembro de 2012
Ultima resposta 21 de dez. de 2012
Respostas 2
Participantes 3