zoukankan      html  css  js  c++  java
  • 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

    博客园Blog: http://www.cnblogs.com/wenziii/
    独立博客: 时光的脚注
    新浪微博:@文子的天空
    本文版权归作者和博客园所有,欢迎转载,转载请注明出处
  • 相关阅读:
    进程与线程
    the art of seo(chapter seven)
    the art of seo(chapter six)
    the art of seo(chapter five)
    the art of seo(chapter four)
    the art of seo(chapter three)
    the art of seo(chapter two)
    the art of seo(chapter one)
    Sentinel Cluster流程分析
    Sentinel Core流程分析
  • 原文地址:https://www.cnblogs.com/wenziii/p/3025654.html
Copyright © 2011-2022 走看看