Search code examples
javaimage-processingstack-overflow

When I run this code I get the stackOverflow error


I have to get the values and I have to match the pixels values in my image. But When I run this code I get the StackOverflowError.

How to increase the stack memory in java to overcome this issue.

public class ImageToText {
    private final int ALPHA = 24;
    private final int RED = 16;
    private final int GREEN = 8;
    private final int BLUE = 0;

    public static void main(String args[]) throws IOException {
        File file = new File("C:\\image.jpg");
        BufferedImage image = ImageIO.read(file);
        int color21=image.getHeight();
        int color31=image.getWidth();
        getRGBA(image,color31,color21);

        for (int i = 0; i < image.getHeight(); i++) 
        {
            for (int j = 0; j < image.getWidth(); j++)
            {
                int color = image.getRGB(j, i);
                int color2=image.getHeight();
                int color3=image.getWidth();
                System.out.println(color2);
            }
        }
    }

    public static int[] getRGBA(BufferedImage img, int x, int y)
    {
        int[] color = new int[4];
        int[] originalPixel =  getRGBA(img,x,y);

        for (int i=0;i<img.getWidth();i++)
        {
            for (int j=0;j<img.getHeight();j++)
            {
                int[] color1 =  getRGBA(img,i,j);

                if (originalPixel[0] == color1[0] && originalPixel[1] == color1[1] && originalPixel[2] == color1[2] && originalPixel[3] == color1[3])
                {
                    img.setRGB(i, j,Color.red.getRGB());
                }
                else
                {
                    img.setRGB(i, j,Color.yellow.getRGB());
                }
            }
        }
        return color;
    }
}

How to overcome this Error?


Solution

  • getRGBA calls itself infinitely:

    public static int[] getRGBA(BufferedImage img, int x, int y)
    
      {
    
    int[] color = new int[4];
    
    
     int[] originalPixel =  getRGBA(img,x,y);
    

    This sort of thing causes a StackOverflowError.

    Consider adding the base case of recursion, so that your code doesn't always call itself and has a "way out".