Thumbnail

2 respostas
andreacerqueira

Estou tentando gerar miniaturas das imagens mas não estou entendendo pq em java se utiliza tipos bytes, eu salvei apenas o nome das imagens no banco de dados e pretendia gerar a thumb com alguma classe já pronta, o problema é que o que eu tenho visto na net utiliza bytes, não sei como a imagem fica guarda no bd assim.
Esse foi o ultima classe que achei pra gerar as thumbnails, mas não rolou pelo motivo que falei.

package pack.vinhos.control;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class ImageGetter extends HttpServlet {
    
    public static void main(String[] args) {
        
    }
    
    @Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String productNumber = null;
        productNumber = request.getParameter("idImg");
        getImage(response, productNumber);
    }

    public void getImage(HttpServletResponse response,
            String productNumber) throws ServletException, IOException {
        try {
            //setup the database connection
            Connection imageConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "");
            
            //SQL statement to query the database
            PreparedStatement imagePS = imageConn.prepareCall("SELECT img FROM vinhos WHERE id = '" + productNumber + "'");
            imagePS.setQueryTimeout(0);

            //the ResultSet object to hold the query results
            ResultSet RSImage = imagePS.executeQuery();

            //create a boolean datatype that is initialized to //true if the ResultSet is empty (no image found)
            boolean noRecords = !RSImage.next();

            //if the ResultSet is empty, close it
            if (noRecords) {
                RSImage.close();
            } else { //if it contains data, go ahead with the image //fetching
                //set the content type for an image (image/gif //will still display jpgs and possibly bmps
                //in Internet Explorer)
                response.setContentType("image/gif");
                ServletOutputStream out = response.getOutputStream();

                //getBytes is a method of class ResultSet used //to read the ResultSet data into an array of //bytes. This is where the image gets pulled //from the database into an array we can work //with in our code.
                byte imageByteArray[] = RSImage.getBytes("img");
                //String imgByte = "http://localhost:8080/teste/images/" + RSImage.getString("img");
                //byte imageByteArray[] = imgByte.getBytes();
                
                //the content length is set to the length of //the byte array
                response.setContentLength(imageByteArray.length);

                //the byte array is written to the //ServletOutputStream starting with the first //byte and ending with the last
                out.write(imageByteArray, 0, imageByteArray.length);

                //The ServletOutputStream is flushed, the //recordset is closed, and the connection is //closed.
                out.flush();

                RSImage.close();

            }

            imageConn.close();

        } catch (Exception ex) {
            
        }

    }
}

Alguém sabe de uma classe pra isso?
Tipo a timthumbs do php

Obrigado

2 Respostas

andreacerqueira

consegui essa classe, ela não gera a imagem no momento que a pagina carrega, o que é até melhor pois economiza banda e processamento.
ela gera uma unica vez e salva onde eu mandei.
mudei o codigo pa ele pegar o caminho absoluto do site.
essa é a melhor forma mesmo de se gerar thumbnails?

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;

public class ThumbNail2 {

    public static void main(String[] args) throws Exception {
        new ThumbNail2().createThumbnail("155973.jpg", "155973-thumb.jpg", 100, 100);
    }
    
    public void createThumbnail(String imgFilePath, String thumbPath, int thumbWidth, int thumbHeight) throws Exception {

        // getProperty pega o path absoluto e o replace muda a direção da slash(barra) pra pegar o caminho correto
        String pathAbsoluto = System.getProperty("user.dir").replace("\\", "/");
        String caminho = pathAbsoluto + "/web/images/" + imgFilePath;
        //System.out.println(caminho);
        Image image = Toolkit.getDefaultToolkit().getImage(caminho);
        MediaTracker mediaTracker = new MediaTracker(new Container());
        mediaTracker.addImage(image, 0);
        mediaTracker.waitForID(0);
        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }
        BufferedImage thumbImage = new BufferedImage(thumbWidth,
                thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
        
        String caminhoThumb = pathAbsoluto + "/web/images/" + thumbPath;
        System.out.println(caminhoThumb);
        
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(caminhoThumb));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
        int quality = 100;
        param.setQuality((float) quality / 100.0f, false);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(thumbImage);
        out.close();
    }
}
andreacerqueira

Problema :slight_smile:
Se eu der um run file só na classe pra testar a criação dá tudo certo, ele pega o caminho absoluto correto, mas se eu testar o sistema todo no navegador ele pega o caminho errado.

Tipo, rodando só a classe me retorna isso:

Rodando o site isso:

dentro do jsp eu consigo pegar o endereço correto usando

getServletContext().getRealPath("/")

como sou nova em java nem tinha reparado que existia a pasta build que dentro tem uma copia da pasta web, e fiquei na duvida. pq essa pasta build existe? quando o site é lido no navegador ele ve pelo we ou /build/web? quando gero as thumbs devo mandar pra build/web/images ou pra web/images?

Criado 7 de abril de 2012
Ultima resposta 7 de abr. de 2012
Respostas 2
Participantes 1