java图片旋转,
分享于 点击 23022 次 点评:173
java图片旋转,
转载:http://blog.csdn.net/heliang7/article/details/1088845
java实现图片旋转任意角度
下面是核心代码:
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 图片旋转工具
* @author Bob
*
*/
public class RotateImage {
public BufferedImage Rotate(Image src, int angle) {
int src_width = src.getWidth(null);
int src_height = src.getHeight(null);
Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angle);
BufferedImage res = null;
res = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = res.createGraphics();
//将 Graphics2D 上下文的原点平移到当前坐标系中的点 (x, y)
g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
//将当前的 Graphics2D Transform 与平移后的旋转转换连接
g2.rotate(Math.toRadians(angle), src_width / 2, src_height / 2);
g2.drawImage(src, null, null);
g2.dispose();
return res;
}
/**
* 计算图片的新大小
* @param src 图片
* @param angle 角度
* @return
*/
public Rectangle CalcRotatedSize(Rectangle src, int angle) {
if ((angle >= 90) && (angle / 90 % 2 == 1)) {
int temp = src.height;
src.height = src.width;
src.width = temp;
angle = angle % 90;
}
//根据图片高宽求出旋转半径 a的平方+b的平方=c的平方 是四边形的对角线长度/2 为旋转圆的半径
double r = Math.sqrt(src.height * src.height + src.width * src.width)/2;
double len = 2 * Math.sin(Math.toRadians(angle) / 2) * r;
double angle_alpha = (Math.PI - Math.toRadians(angle)) / 2;
double angle_dalta_width = Math.atan((double) src.height / src.width);
double angle_dalta_height = Math.atan((double) src.width / src.height);
int len_dalta_width = (int) (len * Math.cos(Math.PI - angle_alpha - angle_dalta_width));
int len_dalta_height = (int) (len * Math.cos(Math.PI - angle_alpha - angle_dalta_height));
int des_width = src.width + len_dalta_width * 2;
int des_height = src.height + len_dalta_height * 2;
return new Rectangle(new Dimension(des_width, des_height));
}
public static void main(String[] args) {
try {
BufferedImage src = ImageIO.read(new File("E:/A.png"));
//旋转20度
BufferedImage des = new RotateImage().Rotate(src, 20);
//保存到本地
ImageIO.write(des, "png", new File("e:/A2223.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
相关文章
- 暂无相关文章
用户点评