java旋轉圖片


    /**
     * 旋轉角度
     * @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.先旋轉,再平移


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM