Java实现电子签名图片角度旋转

   项目中有用户签名的业务场景,因为手机屏幕限制,前端展示的方案是让用户屏幕横向签名,以至于传到后台的用户签名图片是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;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值