当前位置: 移动技术网 > IT编程>开发语言>Java > java旋转图片

java旋转图片

2018年12月28日  | 移动技术网IT编程  | 我要评论
    /**
     * 旋转角度
     * @param src 源图片
     * @param angel 角度
     * @return 目标图片
     */
    public static bufferedimage rotate(image src, int angel) {
        int src_width = src.getwidth(null);
        int src_height = src.getheight(null);
        // calculate the new image size
        rectangle rect_des = calcrotatedsize(new rectangle(new dimension(
                src_width, src_height)), angel);

        bufferedimage res = null;
        res = new bufferedimage(rect_des.width, rect_des.height,
                bufferedimage.type_int_rgb);
        graphics2d g2 = res.creategraphics();
        // transform(这里先平移、再旋转比较方便处理;绘图时会采用这些变化,绘图默认从画布的左上顶点开始绘画,源图片的左上顶点与画布左上顶点对齐,然后开始绘画,修改坐标原点后,绘画对应的画布起始点改变,起到平移的效果;然后旋转图片即可)
     //平移(原理修改坐标系原点,绘图起点变了,起到了平移的效果,如果作用于旋转,则为旋转中心点) g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);

     //旋转(原理transalte(dx,dy)->rotate(radians)->transalte(-dx,-dy);修改坐标系原点后,旋转90度,然后再还原坐标系原点为(0,0),但是整个坐标系已经旋转了相应的度数 ) g2.rotate(math.toradians(angel), src_width / 2, src_height / 2);
// //先旋转(以目标区域中心点为旋转中心点,源图片左上顶点对准目标区域中心点,然后旋转) // g2.translate(rect_des.width/2,rect_des.height/ 2); // g2.rotate(math.toradians(angel)); // //再平移(原点恢复到源图的左上顶点处(现在的右上顶点处),否则只能画出1/4) // g2.translate(-src_width/2,-src_height/2);
g2.drawimage(src, null, null); return res; } /** * 计算转换后目标矩形的宽高 * @param src 源矩形 * @param angel 角度 * @return 目标矩形 */ private static rectangle calcrotatedsize(rectangle src, int angel) { double cos = math.abs(math.cos(math.toradians(angel))); double sin = math.abs(math.sin(math.toradians(angel))); int des_width = (int)(src.width * cos) + (int)(src.height * sin); int des_height = (int)(src.height * cos) + (int)(src.width * sin); return new java.awt.rectangle(new dimension(des_width, des_height)); }

1.先平移再旋转

 

2.先旋转,再平移

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网