java 切圖 判斷圖片是不是純色/彩色圖片

首先上切圖的代碼spa

/**
     * 圖片剪裁
     * @param x 距離左上角的x軸距離
     * @param y 距離左上角的y軸距離
     * @param width 寬度
     * @param height 高度
     * @param sourcePath 圖片源
     * @param descpath 目標位置
     */
    public static void imageCut(int x, int y, int width, int height, String sourcePath, String descpath) {  
        FileInputStream is = null;  
        ImageInputStream iis = null;  
        try {  
            is = new FileInputStream(sourcePath);  
            String fileSuffix = sourcePath.substring(sourcePath.lastIndexOf(".") + 1);  
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(fileSuffix);  
            ImageReader reader = it.next();  
            iis = ImageIO.createImageInputStream(is);  
            reader.setInput(iis, true);  
            ImageReadParam param = reader.getDefaultReadParam();  
            Rectangle rect = new Rectangle(x, y, width, height);  
            param.setSourceRegion(rect);  
            BufferedImage bi = reader.read(0, param);  
            ImageIO.write(bi, fileSuffix, new File(descpath));  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        } finally {  
            if (is != null) {  
                try {  
                    is.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                is = null;  
            }  
            if (iis != null) {  
                try {  
                    iis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                iis = null;  
            }  
        }  
    }

以上爲切圖代碼,注意:若是不關閉流的話可能會影響其餘代碼對圖片的操做,尤爲是刪除等操做code

再來一個本身寫的判斷是不是純色圖片的代碼,稍微改一下能夠用來判斷是否是彩色圖片orm

/**
     * 判斷是否爲純色
     * @param imgPath 圖片源
     * @param percent 純色百分比,即大於此百分比爲同一種顏色則斷定爲純色,範圍[0-1]
     * @return
     * @throws IOException
     */
    public static boolean isSimpleColorImg(String imgPath,float percent) throws IOException{
        BufferedImage src=ImageIO.read(new File(imgPath));
        int height=src.getHeight();
        int width=src.getWidth();
        int count=0,pixTemp=0,pixel=0;
        for(int i=0;i<width;i++){
            for(int j=0;j<height;j++){
                pixel=src.getRGB(i, j);
                if(pixel==pixTemp) //若是上一個像素點和這個像素點顏色同樣的話,就斷定爲同一種顏色
                    count++;
                else
                    count=0;
                if((float)count/(height*width)>=percent) //若是連續相同的像素點大於設定的百分比的話,就斷定爲是純色的圖片 
                    return true;
                pixTemp=pixel;
            }
        }
        return false;
    }

以上爲本人用來判斷純色的代碼,邏輯比較簡單,具體還要看需求來決定blog

若是是判斷彩色的話,能夠試試以下邏輯:圖片

一、若是有N個像素點各不相同的話能夠斷定爲彩色get

二、若是圖片上有>=N種像素點的話,判斷爲彩色圖片string

以上只是本人的拙見,若是有更好的想法,歡迎分享交流it

相關文章
相關標籤/搜索