运行程序子字符串时出现错误StringIndexOutOfBoundsException

时间:2013-12-18 16:54:05

标签: java substring rgb pixel

我想分析图像中的像素值。我尝试在十六进制像素值的位置2和4处取出值并将其显示在控制台上。我在我的代码中使用子字符串。我尝试运行该程序,但过了一会儿,它显示错误stringoutofboundexception。

显示错误:

java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.substring(String.java:1907)
at getPixelData.getPixelData(getPixelData.java:51)
at getPixelRGB.main(getPixelRGB.java:58)

这些是我的代码:

public class getPixelData 
{
private static final double bitPerColor = 4.0;

public getPixelData()
{

}

public int[] getPixelData(BufferedImage img, int w, int h) throws IOException
{
    int argb = img.getRGB(w, h);
    int rgb[] = new int[]
    {
        (argb >> 16) & 0xff, //red
        (argb >>  8) & 0xff, //green
        (argb      ) & 0xff  //blue
    };

    int red = rgb[0];
    int green = rgb[1]; //RGB Value in Decimal
    int blue = rgb[2];

    System.out.println("\nRGBValue in Decimal --> " + "\nRed: " + red + " Green: " + green + " Blue: " + blue);

    //Convert each channel RGB to Hexadecimal value
    String rHex = Integer.toHexString((int)(red));
    String gHex = Integer.toHexString((int)(green));
    String bHex = Integer.toHexString((int)(blue));

    System.out.println("\nRGBValue in Hexa --> " + "\nRed Green Blue " + rHex + gHex + bHex);

    //Check position 2 and 4 of hexa value for any changes
    String hexa2, hexa4 = "";
    String rgbHexa = rHex + gHex + bHex;

    hexa2 = rgbHexa.substring(1,2);
    System.out.println("\nString RGB Hexa: " + rgbHexa);
    System.out.println("\nSubstring at position 2: " + hexa2);

    //the program stops at here and then displayed the stringoutofboundexception
    hexa4 = rgbHexa.substring(3,4);
    System.out.println("\nSubstring at position 4: " + hexa4);

    ...

    return rgb;
}
}

希望有人帮我解决问题。我还是Java新手。

由于

1 个答案:

答案 0 :(得分:0)

substring方法中,第一个索引是包含的,第二个索引是独占的。另请注意,计数从0开始,因此要从GG获取RRGGBB,您必须致电substring(2, 4)

但是你还必须确保十六进制字符串具有前导零。即,当您将15转换为十六进制时,结果不是0F而只是F,这使得您的字符串比预期的更短。您可能希望使用String.format代替formatting十六进制字符串。

int red = 139, green = 117, blue = 94;
String hex = String.format("%02X%02X%02X", red, green, blue);
String g = hex.substring(2, 4);