栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现切图并且判断图片是不是纯色/彩色图片

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现切图并且判断图片是不是纯色/彩色图片

整理文档,搜刮出一个java实现切图并且判断图片是否是纯色/彩色图片的代码,稍微整理精简一下做下分享。

首先上切图的代码


  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 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; 
      } 
    } 
  }

以上为切图代码,注意:如果不关闭流的话可能会影响其他代码对图片的操作,尤其是删除等操作

再来一个自己写的判断是否是纯色图片的代码,稍微改一下可以用来判断是不是彩色图片


  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=percent) //如果连续相同的像素点大于设定的百分比的话,就判定为是纯色的图片 
   return true;
 pixTemp=pixel;
      }
    }
    return false;
  }

以上为本人用来判断纯色的代码,逻辑比较简单,具体还要看需求来决定

如果是判断彩色的话,可以试试如下逻辑:

1、如果有N个像素点各不相同的话可以判定为彩色

2、如果图片上有>=N种像素点的话,判断为彩色图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/144819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号