简体   繁体   English

不确定如何在while循环中执行此操作

[英]Not sure how to do this while loop

Here is my code: 这是我的代码:

public static void decodeThis(BufferedImage im, String outputFile)
throws FileNotFoundException{
  int w = im.getWidth();
  int h=im.getHeight();
  int[] arr=im.getRGB(0, 0, w, h, null, 0, w);
  int[] eightBit=new int[8];
  int counter=0;
  String[] aString=new String[arr.length];
  PrintStream out=new PrintStream(new File(outputFile));
  double value=0;
  int intVal=0;
  while (counter<arr.length){
    for (int j=0;j<eightBit.length;j++){
        eightBit[j] = arr[j+counter] & 1; //Extracts least significant bit, puts into eightBit array.
    }
    value=0;
    for (int x=0;x<eightBit.length;x++){
        value+=eightBit[x]*(Math.pow(2,x));
    }
    intVal=(int)value;
    out.print((char)intVal);
    counter=counter+8;
}

} }

What I want to do is read, extract, and convert into a character 8 bits from arr while there are still pixels left to read in arr. 我想做的是从arr中读取,提取并转换为8位字符,同时在arr中还有要读取的像素。 For some reason when I run the commented for loop, I get an ArrayIndexOutOfBoundsException. 由于某种原因,当我运行带注释的for循环时,我得到了ArrayIndexOutOfBoundsException。 How do I fix this? 我该如何解决? Thanks in advance! 提前致谢!

The while(counter<arr.length) loop runs counter to the length of arr , and the inner loop accesses arr using j+counter ; while(counter<arr.length)循环与arr的长度counter ,而内部循环使用j+counter访问arr that's guaranteed to run off the end of arr if arr is not an exact multiple of 8. 如果arr不是8的整数倍,则可以保证在arr的末尾运行。

And since arr is the number of bits in the image, it's highly unlikely to be an exact multiple of 8. 而且由于arr是图片中的位数,因此极不可能是8的精确倍数。

更改循环条件。

while (counter <= arr.length - 8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM