图片缩略图的实现,比较灵活[可直接使用]

来源:互联网 发布:适合做网络推广的行业 编辑:程序博客网 时间:2024/06/05 20:47

 iLife's 博客http://blog.csdn.net/fei1502816 



 

其中

originalPath是图片源地址,

newPath是生成缩略图的目的地址,

newWidth、newHeight为缩略图的宽度和高度。

看代码

  1. //改变图像宽和高,维持宽高比     
  2. public static void changeImagePixel(String originalPath,String newPath,int newWidth,int newHeight){     
  3.     //读入内存     
  4.     BufferedImage bi=null;     
  5.     try {     
  6.         bi = ImageIO.read(new File(originalPath));     
  7.              
  8.         //原始宽、高     
  9.         int originalWidth=bi.getWidth();     
  10.         int originalHeight=bi.getHeight();     
  11.         //宽、高比,默认1,即新宽、高和原始宽、高一样     
  12.         double ratio=1;     
  13.              
  14.         //原始宽、高比,最终将维持该比例     
  15.         double originalRatio=(double)originalWidth/originalHeight;     
  16.              
  17.         //文件后缀名     
  18.         String fileType = originalPath.substring(originalPath.lastIndexOf("."));     
  19.         String newFileType="jpg";     
  20.         if(fileType.equals("png") || fileType.equals("PNG")){     
  21.             newFileType="png";     
  22.         }     
  23.              
  24.         //如果图片宽度或者高度超出给定范围     
  25.         if(originalWidth>newWidth || originalHeight>newHeight){     
  26.             if(newWidth < (int)(Math.floor(newHeight * originalRatio))){     
  27.                 //以宽度为准,高度自动,维持原始比例     
  28.                 ratio = (double)newWidth / originalWidth;     
  29.             } else {     
  30.                 //以高度为准,宽度自动,维持原始比例     
  31.                 ratio = (double)newHeight / originalHeight;     
  32.             }     
  33.         }     
  34.              
  35.         AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);     
  36.         Image newImage = op.filter(bi, null);     
  37.         try {     
  38.             //如果目录不存在,则创建     
  39.             //File newPathDir=new File(newPath.substring(0,newPath.lastIndexOf("\\")+1));     
  40.             //if(!newPathDir.exists()) newPathDir.mkdirs();     
  41.                  
  42.             ImageIO.write((BufferedImage) newImage, newFileType, new File(newPath));     
  43.         } catch (IOException e) {     
  44.             // TODO Auto-generated catch block     
  45.             e.printStackTrace();     
  46.         }     
  47.     } catch (IOException e) {     
  48.         // TODO Auto-generated catch block     
  49.         e.printStackTrace();     
  50.     } catch (Exception e) {     
  51.         // TODO Auto-generated catch block     
  52.         e.printStackTrace();     
  53.     }     
  54. }    
0 0
原创粉丝点击