当前位置: 移动技术网 > IT编程>开发语言>Java > java中如何使用BufferedImage判断图像通道顺序并转RGB/BGR

java中如何使用BufferedImage判断图像通道顺序并转RGB/BGR

2019年07月22日  | 移动技术网IT编程  | 我要评论

java中bufferedimage判断图像通道顺序并转rgb/bgr

一般来说java imageio处理读取图像时,一般是rgb或argb格式,但是有的时候,我们需要图像是bgr格式,

比如通过jni将图像矩阵传递给动态库,动态库里用opencv来处理矩阵,而用opencv处理图像时默认通道顺序是bgr,这时就需要一个到bgr转换。

翻了好java api好久,还真没发现有直接将rgb转bgr的方法,于是只好自己写一个,以下是代码片段,用于实现判断bufferedimage图像类型及通道顺序,并将bufferedimage转为rgb或bgr

  实例代码:

 /**
   * @param image
   * @param bandoffset 用于判断通道顺序
   * @return
   */
  private static boolean equalbandoffsetwith3byte(bufferedimage image,int[] bandoffset){
    if(image.gettype()==bufferedimage.type_3byte_bgr){
      if(image.getdata().getsamplemodel() instanceof componentsamplemodel){
        componentsamplemodel samplemodel = (componentsamplemodel)image.getdata().getsamplemodel();
        if(arrays.equals(samplemodel.getbandoffsets(), bandoffset)){
          return true;
        }
      }
    }
    return false;    
  }
  /**
   * 判断图像是否为bgr格式
   * @return 
   */
  public static boolean isbgr3byte(bufferedimage image){
    return equalbandoffsetwith3byte(image,new int[]{0, 1, 2});
  }
  /**
   * 判断图像是否为rgb格式
   * @return 
   */
  public static boolean isrgb3byte(bufferedimage image){
    return equalbandoffsetwith3byte(image,new int[]{2, 1, 0});
  }
  /**
   * 对图像解码返回rgb格式矩阵数据
   * @param image
   * @return 
   */
  public static byte[] getmatrixrgb(bufferedimage image) {
    if(null==image)
      throw new nullpointerexception();
    byte[] matrixrgb;
    if(isrgb3byte(image)){
      matrixrgb= (byte[]) image.getdata().getdataelements(0, 0, image.getwidth(), image.getheight(), null);
    }else{
      // 转rgb格式
      bufferedimage rgbimage = new bufferedimage(image.getwidth(), image.getheight(), 
          bufferedimage.type_3byte_bgr);
      new colorconvertop(colorspace.getinstance(colorspace.cs_srgb), null).filter(image, rgbimage);
      matrixrgb= (byte[]) rgbimage.getdata().getdataelements(0, 0, image.getwidth(), image.getheight(), null);
    } 
    return matrixrgb;
  }
  /**
   * 对图像解码返回bgr格式矩阵数据
   * @param image
   * @return
   */
  public static byte[] getmatrixbgr(bufferedimage image){
    if(null==image)
      throw new nullpointerexception();
    byte[] matrixbgr;
    if(isbgr3byte(image)){
      matrixbgr= (byte[]) image.getdata().getdataelements(0, 0, image.getwidth(), image.getheight(), null);
    }else{     
      // argb格式图像数据
      int intrgb[]=image.getrgb(0, 0, image.getwidth(), image.getheight(), null, 0, image.getwidth());
      matrixbgr=new byte[image.getwidth() * image.getheight()*3];
      // argb转bgr格式
      for(int i=0,j=0;i<intrgb.length;++i,j+=3){
        matrixbgr[j]=(byte) (intrgb[i]&0xff);
        matrixbgr[j+1]=(byte) ((intrgb[i]>>8)&0xff);
        matrixbgr[j+2]=(byte) ((intrgb[i]>>16)&0xff);
      }
    } 
    return matrixbgr;
  }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网