java - 将旋转角度的图片旋转回去 -【解决生成缩略图导致图片旋转问题】

获取旋转角度,参考这篇随笔

java - 检查是否有旋转角度导致ImageIO获取宽高相反 - 岑惜 - 博客园 (cnblogs.com)

旋转回去,工具类

复制代码
import java.awt.*;
import java.awt.image.BufferedImage;

public class RotateImageUtil {

    /**
     * 对图片进行旋转
     *
     * @param src   被旋转图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    public static BufferedImage Rotate(Image src, int angel) {
        int srcWidth = src.getWidth(null);
        int srcHeight = src.getHeight(null);
        // 计算旋转后图片的尺寸
        Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(
                srcWidth, srcHeight)), angel);
        BufferedImage res = null;
        res = new BufferedImage(rect_des.width, rect_des.height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = res.createGraphics();
        // 进行转换
        g2.translate((rect_des.width - srcWidth) / 2,
                (rect_des.height - srcHeight) / 2);
        g2.rotate(Math.toRadians(angel), (double) srcWidth / 2, (double) srcHeight / 2);
        g2.drawImage(src, null, null);
        return res;
    }

    /**
     * 计算旋转后的图片
     *
     * @param src   被旋转的图片
     * @param angel 旋转角度
     * @return 旋转后的图片
     */
    private static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // 如果旋转的角度大于90度做相应的转换
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angelAlpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angelDeltaWidth = Math.atan((double) src.height / src.width);
        double angelDeltaHeight = Math.atan((double) src.width / src.height);
        int lenDeltaWidth = (int) (len * Math.cos(Math.PI - angelAlpha
                - angelDeltaWidth));
        int lenDeltaHeight = (int) (len * Math.cos(Math.PI - angelAlpha
                - angelDeltaHeight));
        int desWidth = src.width + lenDeltaWidth * 2;
        int desHeight = src.height + lenDeltaHeight * 2;
        return new Rectangle(new Dimension(desWidth, desHeight));
    }
}
View Code
复制代码

使用方法

 BufferedImage  继承了 Image  因此可以使用父类

 

 

posted @   岑惜  阅读(260)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2020-08-28 c# - 按引用内存地址传参 和 按输出传参 的具体使用
2020-08-28 c# - 实体类和有参无参构造函数的具体写法
2020-08-28 c# - 数据类型转换和控制台输入
2020-08-28 c# - 关于位移符号 >> 和 << 的使用
2020-08-28 c# - 接口的写法与基本调用
2020-08-28 c# - 命名规则
2020-08-28 c# - 一个.cs类文件里如何建多个类
点击右上角即可分享
微信分享提示