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


首先上切圖的代碼

/**
     * 圖片剪裁
     * @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;  
            }  
        }  
    }

以上為切圖代碼,注意:如果不關閉流的話可能會影響其他代碼對圖片的操作,尤其是刪除等操作

再來一個自己寫的判斷是否是純色圖片的代碼,稍微改一下可以用來判斷是不是彩色圖片

/**
     * 判斷是否為純色
     * @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;
    }

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

如果是判斷彩色的話,可以試試如下邏輯:

1、如果有N個像素點各不相同的話可以判定為彩色

2、如果圖片上有>=N種像素點的話,判斷為彩色圖片

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


免責聲明!

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



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