2013-05-06 38 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(); 
    } 
} 
相关问题