Guardar porcion de imagen seleccionada

Hola experto, te escribo nuevamente con una duda, es con respecto al programa que me facilitaste de seleccionar una porcion de una imagen, necesito que al seleccionar la imagen con el rectangulo del mouse esta se actualize es decir que donde se encontraba la imagen original se redibuje la porcion seleccionada con el mouse, como asi tambien necesito guardar esa porcion de imagen en un archivo (JPG o formato similar).
Suponiendo que la imagen original es por ejemplo de 300x300 pixeles y selecciono con el mouse una pocion de 100x100 pixeles, que me recomendas?
a.- mostrar la imagen de 100x100 en un tamaño de 300x300? La duda con respecto a esta opcion es si no se va a pixelar la imagen al mostrarla a ese tamaño
b.- mostrar la imagen en el tamaño de 100x100?
Esas son las duda que tengo experto ahunque me estoy inclinando por la opcion "b", desde ya muchas gracias por dedicar tu tiempo a mis necesidades y espero tu respuesta. Un abrazo Fernando

1 respuesta

Respuesta
1
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.io.File;
import javax.imageio.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class SaveImage extends Component {
// Doble buffer para mejor rendimiento
private BufferedImage bi, biFiltered;
int w, h;
JSpinner campoX = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1));
JSpinner campoY = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1));
JSpinner campoWidth = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1));
JSpinner campoHeight = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1));
public SaveImage() {
this.addMouseMotionListener(createMouseMotionListener());
this.addMouseListener(createMouseListener());
try {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(this);
bi = ImageIO.read(jfc.getSelectedFile());
w = bi.getWidth(null);
h = bi.getHeight(null);
if (bi.getType() != BufferedImage.TYPE_INT_RGB) {
BufferedImage bi2 =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics big = bi2.getGraphics();
big.drawImage(bi, 0, 0, null);
biFiltered = bi = bi2;
}
} catch (Exception e) {
System.out.println("Image could not be read");
System.exit(1);
}
}
public void guardarComo() {
try {
JFileChooser jfc = createJFileChooser();
jfc.showSaveDialog(this);
File file = jfc.getSelectedFile();
if ( file == null ){
return;
}
javax.swing.filechooser.FileFilter ff = jfc.getFileFilter();
String fileName = file.getName();
String extension = "jpg";
if ( ff instanceof MyFileFilter){
extension = ((MyFileFilter)ff).getExtension();
fileName = fileName + "." + extension;
}
file = new File(file.getParent(),fileName);
BufferedImage myImage = bi.getSubimage(seleccion.x, seleccion.y, seleccion.width, seleccion.height);
javax.imageio.ImageIO.write(myImage, extension, file);
} catch (Exception e) {
System.out.println(e);
}
}
public JFileChooser createJFileChooser(){
JFileChooser jfc = new JFileChooser();
jfc.setAcceptAllFileFilterUsed(false);
String [] fileTypes = getFormats();
for(int i=0; i<fileTypes.length; i++ ){
jfc.addChoosableFileFilter(new MyFileFilter(fileTypes,fileTypes + " file"));
}
return jfc;
}
/* Return the formats sorted alphabetically and in lower case */
public String[] getFormats() {
String[] formats = javax.imageio.ImageIO.getWriterFormatNames();
java.util.TreeSet<String> formatSet = new java.util.TreeSet<String>();
for (String s : formats) {
formatSet.add(s.toLowerCase());
}
return formatSet.toArray(new String[0]);
}
public void cortarSeleccion(){
BufferedImage myImage = bi.getSubimage(seleccion.x, seleccion.y, seleccion.width, seleccion.height);
bi = biFiltered = myImage;
seleccion.setBounds(new Rectangle(0,0,0,0));
actualizarCampos();
repaint();
}
private MouseListener createMouseListener() {
MouseAdapter adapter = new MouseAdapter(){
public void mouseReleased(MouseEvent e){
esModoSeleccion = false;
}
public void mousePressed(MouseEvent e){
esModoSeleccion = true;
seleccion.setLocation(e.getPoint());
seleccion.setSize(0, 0);
initialPoint = e.getPoint();
}
};
return adapter;
}
private Rectangle seleccion = new Rectangle(0,0,0,0);
private boolean esModoSeleccion = false;
private Point initialPoint = new Point(0,0);
private MouseMotionListener createMouseMotionListener() {
MouseMotionListener adapter = new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
if ( esModoSeleccion ){
if ( e.getPoint().x > initialPoint.x ) seleccion.width = e.getPoint().x - initialPoint.x;
if ( e.getPoint().y > initialPoint.y ) seleccion.height = e.getPoint().y - initialPoint.y;
if ( e.getPoint().x < initialPoint.x ) {
seleccion.width = initialPoint.x - e.getPoint().x;
seleccion.x = e.getPoint().x;
}
if ( e.getPoint().y < initialPoint.y ){
seleccion.height = initialPoint.y - e.getPoint().y;
seleccion.y = e.getPoint().y;
}
actualizarCampos();
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
};
return adapter;
}
protected void actualizarCampos() {
campoX.setValue(new Integer(seleccion.x));
campoY.setValue(new Integer(seleccion.y));
campoHeight.setValue(new Integer(seleccion.height));
campoWidth.setValue(new Integer(seleccion.width));
}
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
public void paint(Graphics g) {
g.drawImage(biFiltered, 0, 0, null);
Graphics2D g2d = (Graphics2D)g;
Rectangle2D rectangle = new Rectangle2D.Double(seleccion.getX(),seleccion.getY(),seleccion.getWidth(),seleccion.getHeight());
g2d.setColor (Color.blue);
g2d.setStroke (new BasicStroke(
1f,
BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND,
1f,
new float[] {2f},
0f));
g2d.draw (rectangle);
}
public static void main(String s[]) {
JFrame f = new JFrame("Save Image Sample");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
SaveImage si = new SaveImage();
f.add("Center", si);
f.add("East",si.createSidePanel());
f.pack();
f.setVisible(true);
}
private JPanel createSidePanel(){
JPanel sidePanel = new JPanel();
JLabel label = new JLabel("Selected rectangle:");
sidePanel.add(label);
sidePanel.add(createLineBreak());
label = new JLabel("X:");
sidePanel.add(label);
sidePanel.add(campoX);
sidePanel.add(createLineBreak());
label = new JLabel("Y:");
sidePanel.add(label);
sidePanel.add(campoY);
sidePanel.add(createLineBreak());
label = new JLabel("Width:");
sidePanel.add(label);
sidePanel.add(campoWidth);
sidePanel.add(createLineBreak());
label = new JLabel("Height:");
sidePanel.add(label);
sidePanel.add(campoHeight);
sidePanel.add(createLineBreak());
JButton boton = new JButton("
<html>
Actualizar<br />rectangulo
</html>
");
boton.addActionListener(createActionListener());
sidePanel.add(boton);
sidePanel.add(createLineBreak());
boton = new JButton("Cortar seleccion");
boton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
cortarSeleccion();
}
});
sidePanel.add(boton);
sidePanel.add(createLineBreak());
boton = new JButton("Guardar seleccion");
boton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
guardarComo();
}
});
sidePanel.add(boton);
sidePanel.setPreferredSize(new Dimension(150,500));
return sidePanel;
}
private ActionListener createActionListener() {
ActionListener adapter = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
seleccion.height = ((Integer)campoHeight.getValue()).intValue();
seleccion.width = ((Integer)campoWidth.getValue()).intValue();
seleccion.x = ((Integer)campoX.getValue()).intValue();
seleccion.y = ((Integer)campoY.getValue()).intValue();
repaint();
}
};
return adapter;
}
private static Component createLineBreak(){
return Box.createRigidArea(new Dimension(150, 0));
}
class MyFileFilter extends javax.swing.filechooser.FileFilter
{
private String extension;
private String description;
public MyFileFilter(String extension,String description){
this.extension = extension;
this.description = description;
}
public boolean accept (File f) {
return f.getName ().toLowerCase ().endsWith ("."+extension)
|| f.isDirectory ();
}
public String getDescription () {
return description;
}
public String getExtension(){
return extension;
}
}
}
No olvides finalizar la pregunta
Hola muchas gracias experto por responder tan rapido, te comento que me da un error en el codigo que me pasaste, estoy trabajando con el IDE netbeans 6.5. Adjunto el codigo donde me da el error especificamente la parte donde esta en negrita
public JFileChooser createJFileChooser(){
JFileChooser jfc = new JFileChooser();
jfc.setAcceptAllFileFilterUsed(false);
String[] fileTypes = getFormats();
for(int i=0; i
jfc.addChoosableFileFilter(new MyFileFilter(fileTypes,fileTypes + " file"));
}
return jfc;
}
Este es el cartel de aviso que me da el IDE
cannot find symbol
symbol: constructor MyFileFilter(Java.lang.String[],Java.lang.String)
Este es el constructor que figura en codigo
public MyFileFilter(String extension,String description){
this.extension = extension;
this.description = description;
}

La opcion que me da el IDE de solucionar el problema es crear el siguiente constructor, pero con el ya surgen muchos otros errores
private MyFileFilter(String[] fileTypes, String string)
Estuve investigando para ver cual podria ser el posible error pero no encontre nada al respecto es por ello que nuevamente recurro a vos, espero no molestarte con mis preguntas, espero tu respuesta. Saludos Fernando
Hola experto te envio nuevamente la porcion de codigo donde me da error por que en el anterior msj no se copio bien la parte del for,salio incompleto y no queria que pensaras que podria ser parte del problema. Un abrazo Fernando
public JFileChooser createJFileChooser(){
JFileChooser jfc = new JFileChooser();
jfc.setAcceptAllFileFilterUsed(false);
String[] fileTypes = getFormats();
for(int i=0; i<fileTypes.length; i++ ){
jfc.addChoosableFileFilter(new MyFileFilter(fileTypes,fileTypes + " file"));
}
return jfc;
}
Ese es error del editor de todo expertos, que se come los corchetes ... debes colocarle los corchetes para acceder la posicion i-esima del array fileTypes ...
jfc.addChoosableFileFilter(new MyFileFilter(fileTypes[ i ],fileTypes [ i ] + " file"));
Hola experto la verdad que funciona perfectamente con la linea de codigo que me proporcionaste, solo tengo una duda y espero que sea la ultima para no molestarte mas con mis preguntas. La cual es que una vez que selecciono con el mouse la porcion de imagen que deseo presiono el boton "cortar seleccion" y aparece la nueva imagen que habia seleccionado y en este momento es cuando aparece el error cuando quiero guardar la imagen cortada presiono sobre "guardar seleccion" y este es el error que me proporciona el IDE:
java.awt.image.RasterFormatException: negative or zero width
Todo lo demas funciona perfectamente, espero tu respuesta y nuevamente muchas gracias por todo!!!!
Tengo que replicar el error... necesito que me digas como fue que obtuviste el error... ¿de qué dimensiones era el rectangulo que seleccionaste?
Hola experto, probe muchas veces y ahora no me sale el error, debe ser que no estoy seleccionando la misma dimension del rectangulo que seleccione con anterioridad, en caso que mas adelante me surja nuevamente el problema te estare escribiendo.....
Bueno experto no sabria como agradecerte, la verdad que me salvaste en muchos problemas que me surgieron. Muchas gracias por brindar tus conocimientos a gente que recien empieza en el mundo de java.... Te felicito y espero que sigas de este modo.

Añade tu respuesta

Haz clic para o

Más respuestas relacionadas