1. import java.awt.Color;
2. import java.awt.Graphics2D;
3. import java.awt.Transparency;
4. import java.awt.geom.AffineTransform;
5. import java.awt.image.AffineTransformOp;
6. import java.awt.image.BufferedImage;
7. import java.io.ByteArrayInputStream;
8. import java.io.ByteArrayOutputStream;
9. import java.io.IOException;
10. import java.io.InputStream;
11.
12. import javax.imageio.ImageIO;
13. import javax.imageio.stream.ImageOutputStream;
14.
15. public class ImageChange {
16.
17. public static InputStream rotateImg(BufferedImage image, int degree, Color bgcolor) throws IOException {
18.
19. int iw = image.getWidth();//原始图象的宽度
20. int ih = image.getHeight();//原始图象的高度
21. int w = 0;
22. int h = 0;
23. int x = 0;
24. int y = 0;
25. = degree % 360;
26. if (degree < 0)
27. = 360 + degree;//将角度转换到0-360度之间
28. double ang = Math.toRadians(degree);//将角度转为弧度
29.
30. /**
31. *确定旋转后的图象的高度和宽度
32. */
33.
34. if (degree == 180 || degree == 0 || degree == 360) {
35. = iw;
36. = ih;
37. } else if (degree == 90 || degree == 270) {
38. = ih;
39. = iw;
40. } else {
41. //int d = iw + ih;
42. //w = (int) (d * Math.abs(Math.cos(ang)));
43. //h = (int) (d * Math.abs(Math.sin(ang)));
44. double cosVal = Math.abs(Math.cos(ang));
45. double sinVal = Math.abs(Math.sin(ang));
46. = (int) (sinVal*ih) + (int) (cosVal*iw);
47. = (int) (sinVal*iw) + (int) (cosVal*ih);
48. }
49.
50. = (w / 2) - (iw / 2);//确定原点坐标
51. = (h / 2) - (ih / 2);
52. BufferedImage rotatedImage = new BufferedImage(w, h, image.getType());
53. Graphics2D gs = (Graphics2D)rotatedImage.getGraphics();
54. if(bgcolor==null){
55. = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
56. }else{
57. .setColor(bgcolor);
58. .fillRect(0, 0, w, h);//以给定颜色绘制旋转后图片的背景
59. }
60.
61. AffineTransform at = new AffineTransform();
62. .rotate(ang, w / 2, h / 2);//旋转图象
63. .translate(x, y);
64. AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
65. .filter(image, rotatedImage);
66. image = rotatedImage;
67.
68. ByteArrayOutputStream byteOut= new ByteArrayOutputStream();
69. ImageOutputStream iamgeOut = ImageIO.createImageOutputStream(byteOut);
70.
71. ImageIO.write(image, "png", iamgeOut);
72. InputStream inputStream = new ByteArrayInputStream(byteOut.toByteArray());
73.
74. return inputStream;
75. }
76.
77.
78. }