JAVA实现图片的旋转

代码

    /**
     * 旋转图片
     */
    public static BufferedImage rotateImage(BufferedImage originalImage, double angle) {
        // 获取原始图像的宽度和高度
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();

        // 计算旋转后的图像的大小
        double radian = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(radian));
        double cos = Math.abs(Math.cos(radian));

        int newWidth = (int) Math.floor(width * cos + height * sin);
        int newHeight = (int) Math.floor(width * sin + height * cos);

        // 创建一个新的 BufferedImage 来存储旋转后的图像
        BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());

        // 计算旋转中心
        int centerX = newWidth / 2;
        int centerY = newHeight / 2;
        int originalCenterX = width / 2;
        int originalCenterY = height / 2;

        // 创建 Graphics2D 对象
        Graphics2D graphics2D = rotatedImage.createGraphics();

        // 设置旋转的变换
        AffineTransform transform = new AffineTransform();
        transform.rotate(radian, centerX, centerY);
        transform.translate(centerX - originalCenterX, centerY - originalCenterY);

        // 应用旋转变换
        graphics2D.setTransform(transform);

        // 绘制原始图像到旋转后的图像
        graphics2D.drawImage(originalImage, 0, 0, null);

        // 释放 Graphics2D 对象
        graphics2D.dispose();

        return rotatedImage;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值