Java圖片裁剪


public static void main(String[] args) throws IOException {
       String path = "C:/Users/yang/Desktop/source.jpg";
      
       BufferedImage bufferedImage = ImageIO.read(new File(path)); 
        int width = bufferedImage.getWidth(); 
        int height = bufferedImage.getHeight(); 
        System.out.println(width+"---"+height);
       
        String targetpath = "C:/Users/yang/Desktop/";
       
        int i = 0,cutwidth = 2000;
       
        while(height>0 && height%cutwidth!=0){
        System.out.println("第"+(i+1)+"次");  
           cut(path, targetpath+i+".jpg", 0, i*cutwidth, width, cutwidth);
           height -= cutwidth;
           i++;
        }
    }
public static void cut(String srcpath,String subpath,int x,int y,int width,int height) throws IOException{ 
       
        FileInputStream is = null ;
        ImageInputStream iis =null ;
       
        try{   
            //讀取圖片文件
            is = new FileInputStream(srcpath); 
              
            /**//*
             * 返回包含所有當前已注冊 ImageReader 的 Iterator,這些 ImageReader
             * 聲稱能夠解碼指定格式。參數:formatName - 包含非正式格式名稱 .
             *(例如 "jpeg" 或 "tiff")等。
             */
            String suffix = srcpath.substring(srcpath.lastIndexOf(".")+1);
  
  
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffix);  
            ImageReader reader = it.next(); 
            //獲取圖片流 
            iis = ImageIO.createImageInputStream(is);
                 
            /**//*
             * <p>iis:讀取源.true:只向前搜索 </p>.將它標記為‘只向前搜索’。
             * 此設置意味着包含在輸入源中的圖像將只按順序讀取,可能允許 reader
             *  避免緩存包含與以前已經讀取的圖像關聯的數據的那些輸入部分。
             */
            reader.setInput(iis,true) ;
              
            /**//*
             * <p>描述如何對流進行解碼的類<p>.用於指定如何在輸入時從 Java Image I/O
             * 框架的上下文中的流轉換一幅圖像或一組圖像。用於特定圖像格式的插件
             * 將從其 ImageReader 實現的 getDefaultReadParam 方法中返回
             * ImageReadParam 的實例。 
             */
            ImageReadParam param = reader.getDefaultReadParam(); 
               
            /**//*
             * 圖片裁剪區域。Rectangle 指定了坐標空間中的一個區域,通過 Rectangle 對象
             * 的左上頂點的坐標(x,y)、寬度和高度可以定義這個區域。
             */ 
            Rectangle rect = new Rectangle(x, y, width, height); 
              
                
            //提供一個 BufferedImage,將其用作解碼像素數據的目標。 
            param.setSourceRegion(rect); 
  
            /**//*
             * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象,並將
             * 它作為一個完整的 BufferedImage 返回。
             */
            BufferedImage bi = reader.read(0,param);                
        
            //保存新圖片 
            ImageIO.write(bi, "jpg", new File(subpath));     
        }
          
        finally{
            if(is!=null)
               is.close() ;       
            if(iis!=null)
               iis.close();  
        } 
       
    } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM