2011-12-08 43 views
0

我一直在創建一個函數,它像Java中的BufferedImage類的繪畫桶工具一樣工作。它使用遞歸來執行填充。可悲的是,當我執行代碼時,它給了我一個java.lang.StackOverflowError。我還發現,它不識別BaseColor,因爲當我使用System.out.println檢查BaseColor的「紅色」顏色通道時,它給了我一個零,那裏應該是255。(顏色是白色)以下是代碼:StackOverflowError在Java中「填充圖像」功能

public static void BufferedImageFill(BufferedImage bufferedImage, int FillX, int FillY, int FillRed, int FillGreen, int FillBlue, int FillAlpha, int Tolerance, boolean IsFirstPixel, Color BaseColor) { 
    if (IsFirstPixel == true) { 
     BaseColor = new Color(RGBAValuesToInt(BufferedImageGetPixelARGB(bufferedImage, "R", FillX, FillY), BufferedImageGetPixelARGB(bufferedImage, "G", FillX, FillY), BufferedImageGetPixelARGB(bufferedImage, "B", FillX, FillY), BufferedImageGetPixelARGB(bufferedImage, "A", FillX, FillY))); 
    } 
    if (FillX >= 0 && FillY >= 0 && FillX < bufferedImage.getWidth() && FillY < bufferedImage.getHeight()) { 
     int ThisR = BufferedImageGetPixelARGB(bufferedImage, "R", FillX, FillY); 
     int ThisG = BufferedImageGetPixelARGB(bufferedImage, "G", FillX, FillY); 
     int ThisB = BufferedImageGetPixelARGB(bufferedImage, "B", FillX, FillY); 
     if (Math.abs(ThisR - BaseColor.getRed()) <= Tolerance && Math.abs(ThisG - BaseColor.getGreen()) <= Tolerance && Math.abs(ThisB - BaseColor.getBlue()) <= Tolerance) { 
      bufferedImage.setRGB(FillX, FillY, RGBAValuesToInt(FillRed, FillGreen, FillBlue, FillAlpha)); 
      BufferedImageFill(bufferedImage, FillX - 1, FillY - 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX - 1, FillY, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX - 1, FillY + 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX, FillY + 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX, FillY - 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX + 1, FillY - 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX + 1, FillY, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
      BufferedImageFill(bufferedImage, FillX + 1, FillY + 1, FillRed, FillGreen, FillBlue, FillAlpha, Tolerance, false, BaseColor); 
     } 
    } 
} 

有人知道爲什麼會發生這種情況嗎?感謝您提供的任何幫助!

-Neil

回答

2

如果我正確地讀取了代碼,當你的方法被調用來填充像素(0,0)時,它會在某個時候調用自身來填充(其他點)像素(1,0)。這個調用反過來將自己調用來再次填充像素(0,0)。這就是爲什麼你有無限遞歸。 (同樣的問題發生在其他相鄰點—每個都會回到並填充導致它被填充的點。)

+0

現在我明白了......感謝您的洞察! – neilf

1

那麼你似乎沒有任何線路來阻止你的遞歸。如果你正在繪畫的顏色在容差範圍內,那麼它將無限地繪製像素並最終溢出堆疊。你需要一條線來檢查它是否已經是正確的顏色,並返回,如果它是。