圖片縮略圖的實現,比較靈活[可直接使用]

 

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


其中

originalPath是圖片源地址,

newPath是生成縮略圖的目的地址,

newWidth、newHeight爲縮略圖的寬度和高度。

看代碼

//改變圖像寬和高,維持寬高比   
public static void changeImagePixel(String originalPath,String newPath,int newWidth,int newHeight){   
    //讀入內存   
    BufferedImage bi=null;   
    try {   
        bi = ImageIO.read(new File(originalPath));   
           
        //原始寬、高   
        int originalWidth=bi.getWidth();   
        int originalHeight=bi.getHeight();   
        //寬、高比,默認1,即新寬、高和原始寬、高一樣   
        double ratio=1;   
           
        //原始寬、高比,最終將維持該比例   
        double originalRatio=(double)originalWidth/originalHeight;   
           
        //文件後綴名   
        String fileType = originalPath.substring(originalPath.lastIndexOf("."));   
        String newFileType="jpg";   
        if(fileType.equals("png") || fileType.equals("PNG")){   
            newFileType="png";   
        }   
           
        //如果圖片寬度或者高度超出給定範圍   
        if(originalWidth>newWidth || originalHeight>newHeight){   
            if(newWidth < (int)(Math.floor(newHeight * originalRatio))){   
                //以寬度爲準,高度自動,維持原始比例   
                ratio = (double)newWidth / originalWidth;   
            } else {   
                //以高度爲準,寬度自動,維持原始比例   
                ratio = (double)newHeight / originalHeight;   
            }   
        }   
           
        AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);   
        Image newImage = op.filter(bi, null);   
        try {   
            //如果目錄不存在,則創建   
            //File newPathDir=new File(newPath.substring(0,newPath.lastIndexOf("\\")+1));   
            //if(!newPathDir.exists()) newPathDir.mkdirs();   
               
            ImageIO.write((BufferedImage) newImage, newFileType, new File(newPath));   
        } catch (IOException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    } catch (IOException e) {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    } catch (Exception e) {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    }   
}  


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章