DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Java - Rotate -90°/90°

10.31.2006
| 25914 views |
  • submit to reddit
        
public BufferedImage rotate90DX(BufferedImage bi)
	{
		int width = bi.getWidth();
		int height = bi.getHeight();
		
		BufferedImage biFlip = new BufferedImage(height, width, bi.getType());
		
		for(int i=0; i<width; i++)
			for(int j=0; j<height; j++)
				biFlip.setRGB(height-1-j, width-1-i, bi.getRGB(i, j));
		
		return biFlip;
	}

	public BufferedImage rotate90SX(BufferedImage bi)
	{
		int width = bi.getWidth();
		int height = bi.getHeight();
		
		BufferedImage biFlip = new BufferedImage(height, width, bi.getType());
		
		for(int i=0; i<width; i++)
			for(int j=0; j<height; j++)
				biFlip.setRGB(j, i, bi.getRGB(i, j));
		
		return biFlip;
	}
    

Comments

Snippets Manager replied on Tue, 2011/09/06 - 5:11am

No issues the below link is working well. :) http://snippets.dzone.com/posts/show/2934 I made a small typo error.

Snippets Manager replied on Tue, 2011/09/06 - 5:11am

Thanks for the post and replies. Also could anyone tell me how to do for rotate 180 and Flip Horizontal and Vertical. http://snippets.dzone.com/posts/show/2934 this is not working as expected...

Snippets Manager replied on Tue, 2009/04/28 - 1:20pm

actually hare had a typo, rotate90SX is the exact same as rotate90DX. try this for 90SX biFlip.setRGB(j, width-1-i, bi.getRGB(i, j));

Snippets Manager replied on Wed, 2009/03/11 - 10:28am

you have a little mistake in your loops, because you are mirroring your image. in rotate90DX(...) you have to use biFlip.setRGB(height-1-j, i, bi.getRGB(i, j)); and in rotate90SX(...) use biFlip.setRGB(height-1-j, i, bi.getRGB(i, j));