2015-12-03 70 views
1

我試圖垂直鏡像像素圖我在Java中;這裏是我的代碼:垂直鏡像Java中的圖像

Dimension coords = pixmap.getSize(); 
for (int x = 0; x < coords.width; x++) { 
    for (int y = 0; y < coords.height; y++) { 
     Color newest = pixmap.getColor(-x, y); 
     pixmap.setColor(x, y, 
      new Color(newest.getRed(), 
         newest.getGreen(), 
         newest.getBlue())); 
    } 
} 

「pixmap」是此實例方法的參數,它本質上是加載的圖像。下面是運行時錯誤,我得到當我嘗試翻轉圖像:

異常在線程「AWT-EventQueue的 - 0」 java.lang.ArrayIndexOutOfBoundsException:座標出界!

任何提示嗎?謝謝!

** 編輯 **

我改變了代碼如下:

Dimension coords = pixmap.getSize(); 
for (int x = 0; x < coords.width; x++) { 
    for (int y = 0; y < coords.height; y++) { 
     Color newest = pixmap.getColor(x, y); 
     if (x < coords.width/2) { 
      pixmap.setColor(((((coords.width/2) - x) * 2) + x), y, 
      new Color(newest.getRed(), 
         newest.getGreen(), 
         newest.getBlue())); 
     } else { 
     pixmap.setColor((x - (((x - (coords.width/2)) * 2))), y, 
      new Color(newest.getRed(), 
         newest.getGreen(), 
         newest.getBlue())); 
     } 
    } 
} 

,我仍然得到同樣的出界異常;不知道我哪裏錯了這段代碼^

+0

那麼,'-100'是否在圖像的範圍內呢? – MadProgrammer

+0

@MadProgrammer哦,哇,沒有想到這一點,我只是想座標,只是試圖翻轉它的Y軸。考慮到從0到coords.width的所有x值,我該如何做到這一點的任何建議都是正面的? – Rohan

+0

'coords.width - x'?但你只想做一半的寬度。請記住,你一定要交換像素 – MadProgrammer

回答

0

Java的是給你一個數組越界異常。您正嘗試訪問給定數組大小內不存在的像素。

顏色最新= pixmap.getColor(-x,y)的;

這是最有可能是什麼問題。
一個像素圖是一個二維數組。雖然我不熟悉的類,它可能看起來是這樣的:

//or whatever your screen is 
int pixels[900][900]; 

這樣說,你的代碼試圖訪問一個負的x座標值的數組。

編輯:

Dimension coords = pixmap.getSize(); 
for (int x = 0; x < coords.width; x++) { 
for (int y = 0; y < coords.height; y++) { 
    pixmap.setColor(x, y, 
     new Color(newest.getRed(), 
        newest.getGreen(), 
        newest.getBlue())); 
} 
    } 

Im去承擔這個代碼將繪製的圖像,因此

Dimension coords = pixmap.getSize(); 
for (int x = 0; x < coords.width; x++) { 
for (int y = 0; y < coords.height; y++) { 
    pixmap.setColor(coords.width-x, y, 
     new Color(newest.getRed(), 
        newest.getGreen(), 
        newest.getBlue())); 
} 
    } 

應繪製的圖像翻轉在x軸上。你可以從這裏找出其餘的東西

+0

我試過coords.width - X,但不幸還是給了我同樣的異常 – Rohan

1

另一種解決方案是使用Graphics2D的負垂直刻度來爲你做翻動......注意這個必須與translate(0,--height)結合起來將圖像帶回到中間。

public static void main(String[] args) throws IOException { 
    BufferedImage image = ImageIO.read(new File("test.jpg")); 

    BufferedImage mirrored = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB); 

    Graphics2D graphics = (Graphics2D)mirrored.getGraphics(); 
    AffineTransform transform = new AffineTransform(); 
    transform.setToScale(1, -1); 
    transform.translate(0, -image.getHeight()); 
    graphics.setTransform(transform); 
    graphics.drawImage(image, 0, 0, null); 

    ImageIO.write(mirrored, "jpg", new File("test-flipped.jpg")); 
} 
+0

這是一個很好的解決方案,我會做,但不幸的是,我僅限於使用上面我所爲這個特定的任務:/。不過謝謝! – Rohan