[英]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.