Servlet中对上传的图片进行大小变换

  做毕业设计,在服务器端Servlet中获取到一个图片文件的输入流并保存到服务器目录后,需要生成一张缩略图另存到其他目录。原以为会很复杂,借助搜索引擎发现javax.imageio.ImageIO类能方便的解决此问题。

直接上代码,这是网上直接找到的已经封装的方法:

 1     /** 
 2      * 长高等比例缩小图片 
 3      * @param srcImagePath 读取图片路径 
 4      * @param toImagePath 写入图片路径 
 5      * @param ratio 缩小比例 
 6      * @throws IOException 
 7      */  
 8     public void reduceImageEqualProportion(String srcImagePath,String toImagePath,int ratio) throws IOException{  
 9         FileOutputStream out = null;  
10         try{  
11             //读入文件    
12             File file = new File(srcImagePath);    
13             // 构造Image对象    
14             BufferedImage src = javax.imageio.ImageIO.read(file);    
15             int width = src.getWidth();    
16             int height = src.getHeight();    
17             // 缩小边长   
18             BufferedImage tag = new BufferedImage(width / ratio, height / ratio, BufferedImage.TYPE_INT_RGB);    
19             // 绘制 缩小  后的图片   
20             tag.getGraphics().drawImage(src, 0, 0, width / ratio, height / ratio, null);    
21             out = new FileOutputStream(toImagePath);    
22             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
23             encoder.encode(tag);    
24         }catch(Exception e){  
25             e.printStackTrace();  
26         }finally{  
27             if(out != null){  
28                 out.close();    
29             }  
30         }  
31     }  

有一篇博文实用javax.imageio封装了许多处理图像的方法,推荐给大家:http://blog.csdn.net/hu_shengyang/article/details/7433988

 

posted @ 2013-04-17 10:36  文子的天空  阅读(874)  评论(0编辑  收藏  举报