Skip to content

Instantly share code, notes, and snippets.

@sanjeevdwivedi
Created January 31, 2018 02:40
Show Gist options
  • Save sanjeevdwivedi/fc8ad9f913c73c1f4b03073e4187bca7 to your computer and use it in GitHub Desktop.
Save sanjeevdwivedi/fc8ad9f913c73c1f4b03073e4187bca7 to your computer and use it in GitHub Desktop.
public BufferedImage rotate(BufferedImage image, int angleDegrees) {
double angle = Math.toRadians(angleDegrees);
double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
int w = image.getWidth(), h = image.getHeight();
int neww = (int)Math.floor(w*cos+h*sin), newh = (int) Math.floor(h * cos + w * sin);
GraphicsConfiguration gc = getGraphicsConfiguration();
BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww - w) / 2, (newh - h) / 2);
g.rotate(angle, w / 2, h / 2);
g.drawRenderedImage(image, null);
g.dispose();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment