Ver Mensaje Individual
  #88 (permalink)  
Antiguo 21/01/2011, 22:18
lpalominop
 
Fecha de Ingreso: septiembre-2008
Mensajes: 8
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: FAQ's de Java

estuvo muy bueno en verdad el codigo esta perfecto y si funciona. felicitaciones




Cita:
Iniciado por stock Ver Mensaje
Tema: Java 2D
Pregunta: Como puedo generar Thumbnails en java??
Respuesta: Bueno, primero te explico que un Thumbnail es una pequeña imagen generada de una de mayor tamaño, son para visualizar muchas imagenes en tamaño pequeño.

Con JAVA esto es posible porsupuesto , acontinuacion voy a poner una clase que es la encargada de hacer el trabajo, despues pondre la implementacion de dicha clase.

he puesto comentarios a las partes de codigo mas importante
Código PHP:
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/*
 * Created on Jan 23, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Crysfel Villa
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class Imagen {
    private 
String imgOriginal;
    private 
String imgResult;
    private 
int calidad;
    private 
int width;
    private 
int height;
    
    
    public 
void resize()throws Exception{
        
//Cargamos la imagen y la preparamos para manipularla
        
Image image Toolkit.getDefaultToolkit().getImage(imgOriginal);
        
MediaTracker mediaTracker = new MediaTracker(new Container());
        
mediaTracker.addImage(image0);
        
mediaTracker.waitForID(0);
        
//Sacamos la proporcion de las nuevas medidas
        
double tnsPro = (double)width/(double)height;
        
//Calculamos la proporcion de la imagen original
        
int imgWidth image.getWidth(null);
        
int imgHeight image.getHeight(null);
        
double imgPro = (double)imgWidth / (double)imgHeight;
        
//comprobamos cual de las dos medidas introducidas esta desproporcionada
        //para asi corregirla
        
if (tnsPro imgPro) {
            
//asignamos una nueva height a la imagen generada
            //para mantener la proporcion con respecto a la original
            
height = (int)(width imgPro);
        } else {
            
//lo mismo pero con el width
            
width = (int)(height imgPro);
        }
        
        
//Creamos la imagen a generar, con los atributos requeridos, ancho, algo, y
        //el ultimo parametro especifica que vamos a guardar la imagen en formato "8-bit RGB"
        //que es un formato compatible con sistemas basados en Solaris o Windows
        //hay mas formatos, ver http://java.sun.com/j2se/1.4.2/docs/api/java/awt/image/BufferedImage.html
        
BufferedImage tnsImg = new BufferedImage(width,heightBufferedImage.TYPE_INT_RGB);
        
Graphics2D graphics2D tnsImg.createGraphics();
        
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        
graphics2D.drawImage(image00widthheightnull);
        
        
//Preparamos para escribir la imagen generada en el disco
        
BufferedOutputStream out = new BufferedOutputStream(new    FileOutputStream(imgResult));
        
//creamos el "parseador" para guardar la imagen en formato JPG
        
JPEGImageEncoder encoder JPEGCodec.createJPEGEncoder(out);
        
JPEGEncodeParam param encoder.getDefaultJPEGEncodeParam(tnsImg);

        
//Asignamos la calidad con la que se va a guardar la imagen de 0-100
        
calidad Math.max(0Math.min(calidad100));
        
param.setQuality((float)calidad 100.0ffalse);
        
encoder.setJPEGEncodeParam(param);
        
encoder.encode(tnsImg);
        
out.close(); 
        
//there you go =D
    
}
    
    
    
/**
     * @return Returns the calidad.
     */
    
public int getCalidad() {
        return 
calidad;
    }
    
/**
     * @param calidad The calidad to set.
     */
    
public void setCalidad(int calidad) {
        
this.calidad calidad;
    }
    
/**
     * @return Returns the height.
     */
    
public int getHeight() {
        return 
height;
    }
    
/**
     * @param height The height to set.
     */
    
public void setHeight(int height) {
        
this.height height;
    }
    
/**
     * @return Returns the imgOriginal.
     */
    
public String getImgOriginal() {
        return 
imgOriginal;
    }
    
/**
     * @param imgOriginal The imgOriginal to set.
     */
    
public void setImgOriginal(String imgOriginal) {
        
this.imgOriginal imgOriginal;
    }
    
/**
     * @return Returns the imgResult.
     */
    
public String getImgResult() {
        return 
imgResult;
    }
    
/**
     * @param imgResult The imgResult to set.
     */
    
public void setImgResult(String imgResult) {
        
this.imgResult imgResult;
    }
    
/**
     * @return Returns the width.
     */
    
public int getWidth() {
        return 
width;
    }
    
/**
     * @param width The width to set.
     */
    
public void setWidth(int width) {
        
this.width width;
    }

Ok, pues como veraz, esta clase tiene las propiedades con las que quieres que se genere el TNS, y el metodo para generarlos se llama resize().

ahora pongo la forma de uso.

Código PHP:
/*
 * Created on Jan 23, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author Crysfel Villa
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

public class Thumbnail {
    public static 
void main(String[] argsthrows Exception {
        
Imagen img = new Imagen();
        
//seleccionamos la imagen a modificar
        
img.setImgOriginal("09.jpg");
        
//el nombre con el cual se generara el TNS
        
img.setImgResult("tns.jpg");
        
//la calidad
        
img.setCalidad(100);
        
//las nuevas medidas, deben ser proporcionales
        //aunque si alguna no lo es, la clase lo corrige
        
img.setWidth(90);
        
img.setHeight(60);
        
        
//there u go ;)
        
img.resize();
    }

Ok, cabe aclarar que la clase tambien se puede usar en algun servlet o en un JSP, en fin, la puedes usar donde quieras

have funnnnnnnnnn