2014-10-06 63 views
0

我有一個方法需要一個字符串和一個整數作爲參數。該方法基本上返回原始圖像的較小的裁剪部分。該字符串是路徑和我在一個switch語句中使用的整數,用於我需要的特定部分,我嘗試了打印輸出,但無論出於何種原因,x和y保持在0,即使我知道我正在獲取高度的值和寬度。返回圖標不能正常工作的方法

private Icon extractIcon(String path, int i){ 
    // reads the image into a BufferedImage object 
    BufferedImage image=null; 
    try{ 
     image = ImageIO.read(new File(path)); 
    } 
    catch(IOException e){ 
     System.err.println("Image not found"); 
     System.exit(1); 
    } 
    height = image.getHeight(); 
    width = image.getWidth(); 
    // allocates another BufferedImage object whose size is 
    // the same as the one of the wanted icon 
    BufferedImage part = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); 

    switch(i){ 
    case 1: 
     x = 0; 
     y = 0; 
     break; 
    case 2: 
     x = width*(1/3); 
     y = 0; 
     break; 
    case 3: 
     x = width*(2/3); 
     y = 0; 
     break; 
    case 4: 
     x = 0; 
     y = height*(1/3); 
     break; 
    case 5: 
     x=width*(1/3); 
     y=height*(1/3); 
     break; 
    case 6: 
     x=width*(2/3); 
     y=height*(1/3); 
     break; 
    case 7: 
     x = 0; 
     y=height*(2/3); 
     break; 
    case 8: 
     x = width*(1/3); 
     y = height*(2/3); 
     break; 
    } 

    //Intializes leftTopX and leftTopY for each button after switch 
    leftTopX = width*(1/3)+x; 
    leftTopY = height*(1/3)+y; 

    // copies the data from "image" to "part" 
    System.out.println(x + " xy " + y); 
    System.out.println(leftTopY + " leftxy " + leftTopX); 
    for(;x<width;x++){ 
     for(;y<height;y++){ 
      part.setRGB(x,y, image.getRGB(x+leftTopX, y+leftTopY)); 
     } 
    } 

    // creates an icon whose content is already in "part" 
    ImageIcon icon = new ImageIcon(); 
    icon.setImage(part); 

    // returns to the caller 
    return icon; 
} 

回答

0

你做一個整數除法...

x = width*(1/3); 
y = 0; 

1/3等於0

你應該嘗試使用一個floatdouble作爲除數...

x = width*(1/3f); 

x = (int)(width*(1/3.0)); 

例如...

+0

噢,親愛的主,你是對的... – user111702 2014-10-06 22:24:54

+0

是的,我做過這一百萬次;) – MadProgrammer 2014-10-06 22:25:34

+0

總是與整數除法哈哈,非常感謝! – user111702 2014-10-06 22:31:41

0

您在交換機箱中遺失了斷路器。

還請記住爲您正在使用的語言添加標籤。

+0

好吧,我加入了break語句,但我仍然在x和y – user111702 2014-10-06 21:51:51

+0

你怎麼稱呼這種方法得到0和0。 (還有:如何重命名我,或者甚至更好:使其成爲一個枚舉:} - 順便說一句:你是否試圖打印寬度和高度,聽起來像他們是0 – MTilsted 2014-10-06 22:00:50

+0

我打印他們在每一個點,他們都很好我注意到switch語句,並將問題隔離開來,但我不知道爲什麼。我調用這樣的方法:Icon icon1 = extractIcon(path,1); – user111702 2014-10-06 22:02:54