2013-05-06 53 views
1

我有一張圖像,我想按一些x,y值進行移位然後保存。我的問題是,我想保留我的原始尺寸,以便在移動圖像後留下x和y「空白」空間。在保持尺寸的情況下移位圖像

另外,有沒有什麼辦法可以將「空白」空間設置爲黑色?

示例:我將600x600圖像向下移動45,然後向左移動30,以便圖像仍然是600x600,但結果是「高度」爲45,空白寬度爲30。

到目前爲止,我一直在使用的BufferedImagegetSubimage方法,試圖解決這個問題,但我似乎無法恢復到原來的尺寸。

關於如何解決這個問題的任何想法?

回答

2

你可以通過創建一個新的緩衝圖像並繪製到它。

// Create new buffered image 
BufferedImage shifted = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
// Create the graphics 
Graphics2D g = shifted.createGraphics(); 
// Draw original with shifted coordinates 
g.drawImage(original, shiftx, shifty, null); 

希望這個工程。

+0

呀,改變了這一切。 – 2013-05-06 15:23:16

+0

令人驚歎,非常簡單。非常感謝你。 – DashControl 2013-05-06 15:38:23

1
public BufferedImage shiftImage(BufferedImage original, int x, int y) { 
     BufferedImage result = new BufferedImage(original.getWidth() + x, 
       original.getHeight() + y, original.getType()); 
     Graphics2D g2d = result.createGraphics(); 
     g2d.drawImage(original, x, y, null); 
     return result; 
    } 

應該工作。

保存

public void SaveImage(BufferedImage image, String filename) { 
    File outputfile = new File(filename + ".png"); 
    try { 
     ImageIO.write(image, "png", outputfile); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
相關問題