[英]When I run this code I get the stackOverflow error
我必须获取值,并且必须匹配图像中的像素值。 但是,当我运行此代码时,我得到了StackOverflowError
。
如何在Java中增加堆栈内存来克服此问题。
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;
}
}
如何克服这个错误?
getRGBA无限调用自己:
public static int[] getRGBA(BufferedImage img, int x, int y)
{
int[] color = new int[4];
int[] originalPixel = getRGBA(img,x,y);
这种事情会导致StackOverflowError。
考虑添加递归的基本情况 ,这样您的代码就不会总是自己调用并具有“出路”。
函数getRGBA的这一行:
int[] originalPixel = getRGBA(img,x,y);
这将导致无限递归。
从main
方法中,您将调用以下getRGBA
方法。 在getRGBA
方法内部,您将再次调用该方法。 这使得没有退出条件的循环/递归执行。
public static int[] getRGBA(BufferedImage img, int x, int y) {
int[] color = new int[4];
int[] originalPixel = getRGBA(img,x,y);
}
您必须在方法调用周围添加一些条件,以便停止递归执行。 您的功能不够清晰,无法建议您可以设置什么条件。
public static int[] getRGBA(BufferedImage img, int x, int y) {
int[] color = new int[4];
if (some condition which becomes true) {
int[] originalPixel = getRGBA(img,x,y);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.