整理文檔,搜刮出一個(gè)java實(shí)現(xiàn)切圖并且判斷圖片是否是純色/彩色圖片的代碼,稍微整理精簡(jiǎn)一下做下分享。
首先上切圖的代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
/** * 圖片剪裁 * @param x 距離左上角的x軸距離 * @param y 距離左上角的y軸距離 * @param width 寬度 * @param height 高度 * @param sourcePath 圖片源 * @param descpath 目標(biāo)位置 */ 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 ; } } } |
以上為切圖代碼,注意:如果不關(guān)閉流的話可能會(huì)影響其他代碼對(duì)圖片的操作,尤其是刪除等操作
再來一個(gè)自己寫的判斷是否是純色圖片的代碼,稍微改一下可以用來判斷是不是彩色圖片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
/** * 判斷是否為純色 * @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) //如果上一個(gè)像素點(diǎn)和這個(gè)像素點(diǎn)顏色一樣的話,就判定為同一種顏色 count++; else count= 0 ; if (( float )count/(height*width)>=percent) //如果連續(xù)相同的像素點(diǎn)大于設(shè)定的百分比的話,就判定為是純色的圖片 return true ; pixTemp=pixel; } } return false ; } |
以上為本人用來判斷純色的代碼,邏輯比較簡(jiǎn)單,具體還要看需求來決定
如果是判斷彩色的話,可以試試如下邏輯:
1、如果有N個(gè)像素點(diǎn)各不相同的話可以判定為彩色
2、如果圖片上有>=N種像素點(diǎn)的話,判斷為彩色圖片
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/inkflower/p/6642089.html