项目中有用户签名的业务场景,因为手机屏幕限制,前端展示的方案是让用户屏幕横向签名,以至于传到后台的用户签名图片是90°颠倒的,
所以需要把签名图片角度进行转换,下面是代码实现!
/**
* 电子签名图片旋转角度
* @param degree
* @param imgPath
*/
public static String spin(int degree,String imgPath) throws Exception {
String savePath = FileUtil.rootPath()+File.separator+"tc-client"+File.separator+ "pdfFile"+File.separator+DateUtils.getDateStr()+".png";
int swidth = 0; // 旋转后的宽度
int sheight = 0; // 旋转后的高度
int x; // 原点横坐标
int y; // 原点纵坐标
File file = new File(imgPath);
if (!file.isFile()) {
throw new Exception("ImageDeal>>>" + file + " 不是一个图片文件!");
}
BufferedImage bi = ImageIO.read(file); // 读取该图片
// 处理角度--确定旋转弧度
degree = degree % 360;
if (degree < 0)
degree = 360 + degree;// 将角度转换到0-360度之间
double theta = Math.toRadians(degree);// 将角度转为弧度
// 确定旋转后的宽和高
if (degree == 180 || degree == 0 || degree == 360) {
swidth = bi.getWidth();
sheight = bi.getHeight();
} else if (degree == 90 || degree == 270) {
sheight = bi.getWidth();
swidth = bi.getHeight();
} else {
swidth = (int) (Math.sqrt(bi.getWidth() * bi.getWidth() + bi.getHeight() * bi.getHeight()));
sheight = (int) (Math.sqrt(bi.getWidth() * bi.getWidth() + bi.getHeight() * bi.getHeight()));
}
x = (swidth / 2) - (bi.getWidth() / 2);// 确定原点坐标
y = (sheight / 2) - (bi.getHeight() / 2);
BufferedImage spinImage = new BufferedImage(swidth, sheight,bi.getType());
// 设置图片背景颜色
Graphics2D gs = (Graphics2D) spinImage.getGraphics();
gs.setColor(Color.white);
gs.fillRect(0, 0, swidth, sheight);// 以给定颜色绘制旋转后图片的背景
AffineTransform at = new AffineTransform();
at.rotate(theta, swidth / 2, sheight / 2);// 旋转图象
at.translate(x, y);
AffineTransformOp op = new AffineTransformOp(at,AffineTransformOp.TYPE_BICUBIC);
spinImage = op.filter(bi, spinImage);
File sf = new File(savePath);
ImageIO.write(spinImage, savePath.substring(savePath.lastIndexOf(".")+1), sf); // 保存图片
return savePath;
}
Java实现电子签名图片角度旋转
最新推荐文章于 2024-06-29 03:05:11 发布