KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > servlets > image > ResizeImageServlet


1 package com.dotmarketing.servlets.image;
2
3 import java.awt.Color JavaDoc;
4 import java.awt.Graphics2D JavaDoc;
5 import java.awt.image.BufferedImage JavaDoc;
6
7 import java.io.FileInputStream JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.OutputStream JavaDoc;
10 import java.net.URLEncoder JavaDoc;
11 import java.util.GregorianCalendar JavaDoc;
12 import java.io.BufferedInputStream JavaDoc;
13
14
15 import javax.servlet.ServletException JavaDoc;
16 import javax.servlet.http.HttpServlet JavaDoc;
17 import javax.servlet.http.HttpServletRequest JavaDoc;
18 import javax.servlet.http.HttpServletResponse JavaDoc;
19
20 import org.apache.commons.logging.LogFactory;
21
22 import sun.awt.image.codec.JPEGImageEncoderImpl;
23
24 import com.dotmarketing.beans.Host;
25 import com.dotmarketing.cache.LiveCache;
26 import com.dotmarketing.factories.HostFactory;
27 import com.dotmarketing.factories.InodeFactory;
28 import com.dotmarketing.portlets.files.factories.FileFactory;
29 import com.dotmarketing.portlets.files.model.File;
30 import com.dotmarketing.util.Logger;
31 import com.dotmarketing.util.UtilMethods;
32 import com.sun.image.codec.jpeg.JPEGEncodeParam;
33
34 /**
35  * This servlet resize an image proportionally without placing
36  * that image into a box background. The image generated is with the .png
37  * extension
38  * @author Oswaldo
39  *
40  */

41 public class ResizeImageServlet extends HttpServlet JavaDoc {
42     
43     private static final long serialVersionUID = 1L;
44     int heightThumbnail = 100;
45     int widthThumbnail = 100;
46     
47     /**
48      * resize an image proportionally without placing
49      * that image into a box background. The image generated is with the .png
50      * extension
51      */

52     public void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
53         
54         long time = System.currentTimeMillis();
55         
56         //getFile Inode
57
String JavaDoc inode = request.getParameter("inode");
58         if (!UtilMethods.isSet(inode)) {
59             String JavaDoc url = request.getParameter("path");
60             Host currentHost = HostFactory.getCurrentHost(request);
61             String JavaDoc path = LiveCache.getPathFromCache(url, currentHost);
62             inode = UtilMethods.getFileName(path);
63         }
64         
65         //Set the expiration time
66
GregorianCalendar JavaDoc expiration = new GregorianCalendar JavaDoc();
67         expiration.add(java.util.Calendar.MONTH, 1);
68         java.text.SimpleDateFormat JavaDoc httpDate = new java.text.SimpleDateFormat JavaDoc("EEE, dd MMM yyyy HH:mm:ss z");
69         response.setHeader("Expires", httpDate.format(expiration.getTime()));
70         response.setHeader("Cache-Control", "max-age=2592000");
71         //END Set the expiration time
72

73         String JavaDoc h = request.getParameter("h");
74         String JavaDoc w = request.getParameter("w");
75         
76         String JavaDoc maxh = request.getParameter("maxh");
77         String JavaDoc maxw = request.getParameter("maxw");
78         
79         int height = heightThumbnail;
80         int width = widthThumbnail;
81         int imageWidth = 0;
82         int imageHeight = 0;
83         double imageRatio = 0;
84         
85         try {
86             
87             if (inode != null && inode.length() > 0) {
88                 
89                 File file = (File) InodeFactory.getInode(inode, File.class);
90                 
91                 if (file.getInode() > 0)
92                 {
93                     //Set the size
94
if(UtilMethods.isSet(h) || UtilMethods.isSet(w)){
95                         
96                         if(UtilMethods.isInt(h) && UtilMethods.isInt(w)){
97                             
98                             height = (Integer.parseInt(h) > 0 ? Integer.parseInt(h) : heightThumbnail);
99                             width = (Integer.parseInt(w) > 0 ? Integer.parseInt(w) : widthThumbnail);
100                             
101                         }else if(UtilMethods.isInt(h)){
102                             
103                             height = (Integer.parseInt(h) > 0 ? Integer.parseInt(h) : heightThumbnail);
104                             
105                             //determine thumbnail size from WIDTH and HEIGHT
106
imageWidth = file.getWidth();
107                             imageHeight = file.getHeight();
108                             imageRatio = (double)imageWidth / (double)imageHeight;
109                             
110                             width = (int)(height * imageRatio);
111                             
112                         }else if(UtilMethods.isInt(w)){
113                             
114                             width = (Integer.parseInt(w) > 0 ? Integer.parseInt(w) : widthThumbnail);
115                             
116                             //determine thumbnail size from WIDTH and HEIGHT
117
imageWidth = file.getWidth();
118                             imageHeight = file.getHeight();
119                             imageRatio = (double)imageWidth / (double)imageHeight;
120                             
121                             height = (int)Math.ceil((width / imageRatio));
122                                                         
123                         }
124                         
125                     }else if(UtilMethods.isSet(maxh) && UtilMethods.isSet(maxw)) {
126                         
127                         int maxhint = Integer.parseInt(maxh);
128                         int maxwint = Integer.parseInt(maxw);
129                         int decrease = 0;
130                         
131                         imageWidth = file.getWidth();
132                         imageHeight = file.getHeight();
133                         
134                         imageRatio = (double)imageWidth / (double)imageHeight;
135                         boolean imageFinishied = true;
136                         
137                         width = maxwint;
138                         height = maxhint;
139                         
140                         do {
141                             
142                             if(width <= height ){
143                                 
144                                 width = width - decrease;
145                                 height = (int)Math.ceil((width / imageRatio));
146                                 
147                             } else {
148                                 
149                                 height = height - decrease;
150                                 width = (int)(height * imageRatio);
151                             }
152                             
153                             decrease= 1;
154                             
155                             if(height <= maxhint && width <= maxwint){
156                                 imageFinishied = false;
157                             }
158                             
159                         }while(imageFinishied);
160                         
161                     }
162                     
163                     
164                     // gets file extension
165
String JavaDoc suffix = file.getExtension();
166                     
167                     // gets the real path to the assets directory
168
String JavaDoc filePath = FileFactory.getRealAssetsRootPath();
169                     
170                     // creates the path where to save the working file based on
171
// the inode
172
String JavaDoc workingFileInodePath = String.valueOf(inode);
173                     if (workingFileInodePath.length() == 1) {
174                         workingFileInodePath = workingFileInodePath + "0";
175                     }
176                     
177                     // creates the path with inode{1} + inode{2}
178
workingFileInodePath = workingFileInodePath.substring(0, 1) + java.io.File.separator
179                     + workingFileInodePath.substring(1, 2);
180                     
181                     String JavaDoc thumbExtension = "resized_" + file.getIdentifier() + URLEncoder.encode(request.getQueryString(),"UTF-8");
182                     
183                     //Set the new tumbnail path
184
String JavaDoc thumbnailFilePath = filePath + java.io.File.separator + workingFileInodePath
185                     + java.io.File.separator + thumbExtension + ".png";
186                     
187                     java.io.File JavaDoc thumbFile = new java.io.File JavaDoc(thumbnailFilePath);
188                     Color JavaDoc bgColor = new Color JavaDoc(255,255,255);
189                     
190                     if (!thumbFile.exists() || (request.getParameter("nocache") != null)) {
191                         com.dotmarketing.util.Thumbnail.resizeImageWithNoBox(filePath + java.io.File.separator
192                                 + workingFileInodePath + java.io.File.separator, String.valueOf(inode), suffix,
193                                 thumbExtension, height, width, bgColor);
194                         thumbFile = new java.io.File JavaDoc(thumbnailFilePath);
195                     }
196                     
197                     // set the content type and get the output stream
198
response.setContentType("image/png");
199                     
200                     BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(thumbFile));
201                     OutputStream JavaDoc os = response.getOutputStream();
202                     byte[] buf = new byte[4096];
203                     int i = 0;
204                     
205                     while ((i = bis.read(buf)) != -1) {
206                         os.write(buf, 0, i);
207                     }
208                     
209                     os.close();
210                     bis.close();
211                     LogFactory.getLog(this.getClass()).debug(
212                             "time to build ResizeImage thumbnail: " + (System.currentTimeMillis() - time) + "ms");
213                 }else
214                 {
215                     //set the content type and get the output stream
216
response.setContentType("image/jpeg");
217                     //Construct the image
218
OutputStream JavaDoc os = response.getOutputStream();
219                     JPEGImageEncoderImpl jpegEncode = new JPEGImageEncoderImpl(os);
220                     BufferedImage JavaDoc bufferedImage = new BufferedImage JavaDoc(1,1,BufferedImage.TYPE_INT_RGB);
221                     Graphics2D JavaDoc graphics = bufferedImage.createGraphics();
222                     Color JavaDoc bgColor = new Color JavaDoc(255,255,255);
223                     graphics.setBackground(bgColor);
224                     JPEGEncodeParam encodeParam = jpegEncode.getDefaultJPEGEncodeParam(bufferedImage);
225                     encodeParam.setQuality(1,true);
226                     jpegEncode.setJPEGEncodeParam(encodeParam);
227                     jpegEncode.encode(bufferedImage);
228                 }
229                 
230             }
231         } catch (Exception JavaDoc e) {
232             Logger.debug(ResizeImageServlet.class,"Error creating thumbnail from ResizeImage servlet");
233             e.printStackTrace(System.out);
234         }
235         return;
236     }
237 }
238
Popular Tags