java实现切图并且判断图片是不是纯色/彩色图片
2017-08-15 16:28
796 查看
整理文档,搜刮出一个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种像素点的话,判断为彩色图片
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- java 切图 判断图片是否是纯色/彩色图片
- 判断是否是图片,java实现
- Java 求1-100以内的所有素数,判断一个数是不是素数。Java代码实现附测试结果图
- Java数组反射实现动态的判断一个对象书否是数组,并且对数组进行拆包输出 。。
- java实现输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果
- 一个5位数,判断它是不是回文数,另一种思路JAVA实现
- java 实现BufferedImage和ImageReader两种方式获取图片宽高、判断图片类型、获取图片大小工具类代码以及测试响应结果
- 并行计算----5种方式实现判断是不是素数.Net,Win32,JavaRunnable,OpenMp,JavaThread
- 判断文件类型是否为图片的方法——Java实现
- Java实现:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
- Java数组反射实现动态的判断一个对象书否是数组,并且对数组进行拆包输出 。。
- java数组反射实现动态的判断一个对象是否是数组并且对数组进行拆包输出
- 怎样知道一个数字是不是2的乘方?怎样判断一个数是不是奇数? Java实现
- 并行计算----5种方式实现判断是不是素数.Net,Win32,JavaRunnable,OpenMp,JavaThread
- java实现缩放图像、切割图像、图像类型转换、彩色转黑白、文字水印、图片水印等
- java实现输入两棵二叉树A,B,判断B是不是A的子结构
- java 判断图片是否是彩色
- 14、JAVA 判断一个数/字符串是不是回文?实现字符串的逆序,如“abcd”变成“dcba”
- RadioButtton java代码实现左右带自定义的图片,并且控制字体与图片间距,同时控件长度对其功能。
- Java数组反射实现动态的判断一个对象书否是数组,并且对数组进行拆包输出 。。