• This is default featured slide 1 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 2 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 3 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 4 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 5 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

Mostrando entradas con la etiqueta imagen. Mostrar todas las entradas
Mostrando entradas con la etiqueta imagen. Mostrar todas las entradas

Usar Zoom en imagenes

Alguna ves quisiste darle zoom a una imagen o quisiste agregar esa función a un proyecto tuyo pues ahora te traigo la solución.
Se trata de una clase o librería x decirlo asi que te dará esa habilidad.

package Zoom;

/**
 *
 * @author JONATHAN
 */
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class Zoom extends JPanel {

    private Image FOTO_ORIGINAL;
    private Image FOTO_tmp;
    private BufferedImage Imagen_en_memoria;
    private Graphics2D g2D;
    private boolean con_foto = false;   

    private int valEscalaX=0;
    private int valEscalaY=0;

    /* al crear el objeto se crea con una imagen pasada como parametro*/
    public Zoom(BufferedImage f){
        this.FOTO_ORIGINAL = f;
        this.FOTO_tmp = f;
        this.setSize(f.getWidth(),f.getHeight());
        this.setVisible(true);
        this.con_foto=true;
    }

    @Override
    protected void paintComponent(Graphics g) {
      Graphics2D g2 = (Graphics2D)g;
      if(this.con_foto){
        Imagen_en_memoria = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
        g2D = Imagen_en_memoria.createGraphics();
        g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        //se añade la foto
        g2D.drawImage(FOTO_tmp,0, 0, FOTO_tmp.getWidth(this), FOTO_tmp.getHeight(this), this);
        g2.drawImage(Imagen_en_memoria, 0, 0, this);
      }
    }

    public void Aumentar(int Valor_Zoom){
        //se calcula el incremento
        valEscalaX =  (int) (FOTO_tmp.getWidth(this) * escala(Valor_Zoom) );
        valEscalaY =  (int) (FOTO_tmp.getHeight(this) * escala(Valor_Zoom) );
        //se escala la imagen sumado el nuevo incremento
        this.FOTO_tmp = FOTO_tmp.getScaledInstance((int) (FOTO_tmp.getWidth(this) + valEscalaX), (int) (FOTO_tmp.getHeight(this) + valEscalaY), Image.SCALE_AREA_AVERAGING);
        resize();
    }

    public void Disminuir(int Valor_Zoom){
        valEscalaX =  (int) (FOTO_tmp.getWidth(this) * escala(Valor_Zoom) );
        valEscalaY =  (int) (FOTO_tmp.getHeight(this) * escala(Valor_Zoom) );
        this.FOTO_tmp = FOTO_tmp.getScaledInstance((int) (FOTO_tmp.getWidth(this) - valEscalaX), (int) (FOTO_tmp.getHeight(this) - valEscalaY), Image.SCALE_AREA_AVERAGING);
        resize();
     }

    private float escala(int v){
        return  v/100f;
    }

    public void Restaurar(){
        this.FOTO_tmp = this.FOTO_ORIGINAL;
        resize();
    }

    private void resize(){
        this.setSize(FOTO_tmp.getWidth(this),FOTO_tmp.getHeight(this));
    }
}
Ahora los métodos para operar esta clase son los siguientes en este caso con este abrilos la imagen en un jpanel que estará dentro de un jscrollpane.
El motivo es para que la imagen al dimensionarse en el jpanel no dimensione tambien el jframe que se usara para visualizar el contenido

private void Abrir_Imagen() {
        fileChooser = new JFileChooser();
        fileChooser.setFileFilter(filter);
        fileChooser.setCurrentDirectory(Directorio);
        int result = fileChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                BufferedImage imagen = ImageIO.read(fileChooser.getSelectedFile());
                Cambiar(imagen.getWidth(), imagen.getHeight());
                zoom = new Zoom(imagen);
                this.Panel.removeAll();
                this.Panel.add(zoom);
                this.Panel.repaint();
                this.Directorio = fileChooser.getCurrentDirectory();
            } catch (IOException ex) {
                System.out.println("error: " + ex);
            }
        }
    }
    private void Cambiar(int alto, int ancho) {
        Panel.setPreferredSize(new Dimension(alto, ancho));
        Panel.setSize(alto, ancho);
    }
Ahora como dije zoom nos permitirá aumentar como disminuir entonces se necesitan estos métodos también.

zoom.Aumentar(50);
zoom.Disminuir(50);
zoom.Restaurar();
Donde 50 en ambos casos es el valor a aumentar o disminuir con respecto a su imagen y bueno restaurar es para regresar a las dimensiones anteriores u originales.
Share:

imágenes en java

Los métodos getWidth o getHeight de Image me devuenven -1

El Problema: Si te devuelve -1, significa que no pudo obtener el tamaño, es porque no se cargo la imagen aún

Estas cargando las imágenes de la siguiente manera:


Image imgen = Toolkit.getDefaultToolkit().getImage( getClass().getResource("objeto.jpeg") );
int ancho = imgen.getWidth(null);
int alto = imgen.getHeight(null);
System.out.println("ANCHO:"+ancho+" ALTO:"+alto);

La salida es algo como:

ANCHO:-1 ALTO:-1

Esto es porque Toolkit.getDefaultToolkit().getImage() retorna primero y luego empieza a cargar los pixels.

Solución:
Utilizar la Clase Image Icon para cargar ya que este método retorna cuando se termino de cargar la imagen.

Image imgen = new ImageIcon(getClass().getResource("imagen.gif")).getImage();
int ancho = imgen.getWidth(null);
int alto = imgen.getHeight(null);
System.out.println("ANCHO:"+ancho+" ALTO:"+alto);

La salida es algo como:

ANCHO:50 ALTO:50
Share:

Visitantes

Flag Counter

Popular Posts

Etiquetas

Recent Posts