DashControl
DashControl

Reputation: 284

Shift Image while keeping dimensions

I have an image that I would like to shift by some x, y value and then save. My problem is that I would like to keep my original dimensions, so that there is x and y "blank" space left after shifting my image.

Also, is there any way I can set the "blank" space to black?

Example: I shift a 600x600 image down by 45 and left by 30, so that the image is still 600x600 but the result has a 45 height and 30 width of "blank" space.

So far I have been using getSubimage method of BufferedImage to try and solve this but I cannot seem to return to the original dimensions.

Any ideas on how to solve this problem?

Upvotes: 1

Views: 734

Answers (2)

arynaq
arynaq

Reputation: 6870

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;
    }

Should work.

Saving

 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();
    }
}

Upvotes: 1

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11940

You could do that by creating a new buffered image and drawing on to it.

// 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);

Hope this works.

Upvotes: 2

Related Questions