Search code examples
javasubstringrgbpixel

Error StringIndexOutOfBoundsException while running program substring


I would like to analyze the pixel value inside images. I try to take out value at the position 2 and 4 of hexadecimal pixel values and display it on the console. I'm using substring in my code. I try running the program but after a while, it displayed error stringoutofboundexception.

Error displayed:

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)

These are my code:

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

Hoping for anyone to help me to solve my problem. I'm still new to Java.

Thanks


Solution

  • In the substring method, the first index is inclusive, and the second index is exclusive. Also, note that counting starts with 0, so to get GG from RRGGBB you have to call substring(2, 4).

    But you also have to make sure that the hex-strings have a leading zero. I.e., when you convert 15 to hex, the result is not 0F but just F, making your string shorter than intended. You might want to use String.format instead for formatting the hex string.

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