Article View: es.comp.lenguajes.java
Article #408Problemas al crear un thumbail de una imagen.
From: Ivan Alameda Carballo
Date: Sun, 26 Aug 2007 21:18
Date: Sun, 26 Aug 2007 21:18
146 lines
6575 bytes
6575 bytes
Hola:
Tengo una página web que estoy migrando de asp.net (w3000 + iis 6) a Java
(Linux ubuntu + Apache 2 + Tomcat 6). La aplicación permite subir
imagenes. He intentado dos metodos para generar los thumbails y luego
guardarlos en la la base de datos (a traves del objeto de negocio que
tengo al respecto),pero ningun me funciona:
El primero, es usando el JPEGEncode, pero el problema es que no me
reconoce la imagen como un jpeg. Quizas haya un problema en como la cargo
desde la peticion web, pero en realidad la grabo en mysql perfectamente,
solo me da problemas cuando intento hacer el thumbail, me da una
excepcion: NOt a jpeg file starts: 0x3f.
Os pego el codigo por si podeis echarme un cable, puede que algo este
poniendo mal:
public class uploadPictures extends HttpServlet {
/** Processes requests for both HTTP <code>GET</code> and
<code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
boolean isMultiPart;
isMultiPart = ServletFileUpload.isMultipartContent(request);
DiskFileUpload fu = new DiskFileUpload();
fu.setSizeMax(10240*512);
fu.setSizeThreshold(40960);
fu.setRepositoryPath("/tmp");
try {
Iterator i = fu.parseRequest(request).iterator();
FileItem actual = null;
while (i.hasNext()){
actual = (FileItem)i.next();
String fname = actual.getName();
Photo oPhoto = new Photo();
oPhoto.setDesPhoto("sticked title");
oPhoto.setBytesOriginal(actual.get());
//creating the bufferedImage from a JPEG stream
InputStream in = new
ByteArrayInputStream(actual.get());
JPEGImageDecoder decoder =
JPEGCodec.createJPEGDecoder(in);
BufferedImage image = decoder.decodeAsBufferedImage();
in.close();
//preparing thumbail numbers
int thumbWidth = 150;
int thumbHeight = 150;
double thumbRatio = (double)thumbWidth /
(double)thumbHeight; //ratio for the thumbail
// obtain the picture width and height
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
//it will works if the size of image is bigger than thumbail details
if (imageWidth > 150 || imageHeight > 150) {
double imageRatio = (double)imageWidth /
(double)imageHeight; //ratio in the original image
if (thumbRatio < imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
} else {
thumbWidth = (int)(thumbHeight * imageRatio);
}
// scale it to the new size on-the-fly
BufferedImage thumbImage = new
BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D =
thumbImage.createGraphics();
graphics2D.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION,
java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth,
thumbHeight, null);
try {
ByteArrayOutputStream sout = new
ByteArrayOutputStream();
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(sout);
JPEGEncodeParam param =
encoder.getDefaultJPEGEncodeParam(thumbImage);
int quality = Math.max(0, Math.min(650,
100));
param.setQuality((float)quality / 100.0f,
false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage, param);
oPhoto.setBytesThumb(sout.toByteArray());
sout.close();
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
}
} // end if image width or height
oPhoto.setBytesThumb(actual.get());
oPhoto.setAlbumID(1);
if(oPhoto.getBytesOriginal().length > 1) {
oPhoto.add();
}
}
} catch (FileUploadException exception) {
}
out.close();
}
Si en lugar de esto trato de utilizar el metodo del
BufferedImage.getScaledInstance, me da aún así otro problema no me llega a
cargar nunca el array de bytes como una imagen... en este caso uso el
siguiente codigo:
...
...
while (i.hasNext()){
actual = (FileItem)i.next();
String fname = actual.getName();
Photo oPhoto = new Photo();
oPhoto.setDesPhoto("sticked title");
oPhoto.setBytesOriginal(actual.get());
//creating the bufferedImage from a JPEG stream
// InputStream in = actual.getInputStream();
BufferedImage image = ImageIO.read(actual.getInputStream());
Image ri = image.getScaledInstance(150,150,150);
...
...
Este me falla tambien... por favor cualquier ayuda podra sacarme seguro de
este pozito en el que me encuentro.
Muchas gracias por adelantado.
Technical Details
Message-ID:
<d6mAi.38514$224.26330@news.ono.com>Path:
arc1-ca.pugleaf.net!g2news2.google.com!news2.google.com!news.glorb.com!feed.cgocable.net!news-out.superfeed.net!prop4-west.newsfeeds.com!news-in1.spamkiller.net!newsf01.ono.com!news.ono.com.POSTED!53ab2750!not-for-mailShow Full Headers
Complete Article Headers
X-Google-Thread: 1116f3,845d709a95bdb6c1,start X-Google-Attributes: gid1116f3,public,usenet X-Google-Language: PORTUGUESE,UTF8 Subject: Problemas al crear un thumbail de una imagen. From: Ivan Alameda Carballo <ia030675-dislikespam-@hotmail.com> Date: Sun, 26 Aug 2007 21:18:01 GMT Message-ID: <d6mAi.38514$224.26330@news.ono.com> Lines: 146 NNTP-Posting-Host: 213.37.143.163 Path: arc1-ca.pugleaf.net!g2news2.google.com!news2.google.com!news.glorb.com!feed.cgocable.net!news-out.superfeed.net!prop4-west.newsfeeds.com!news-in1.spamkiller.net!newsf01.ono.com!news.ono.com.POSTED!53ab2750!not-for-mail Newsgroups: es.comp.lenguajes.java X-Trace: news.ono.com 1188163081 213.37.143.163 (Sun, 26 Aug 2007 23:18:01 MEST) User-Agent: pan 0.120 (Plate of Shrimp) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NNTP-Posting-Date: Sun, 26 Aug 2007 23:18:01 MEST