java旋轉圖片


/**
     * 旋轉圖片
     * @param image
     * @param degree
     * @param bgcolor
     * @return
     * @throws IOException
     */
    private InputStream rotateImg(BufferedImage image, int degree, Color bgcolor) throws IOException {
        int iw = image.getWidth();//原始圖象的寬度
        int ih = image.getHeight();//原始圖象的高度
        int w = 0;
        int h = 0;
        int x = 0;
        int y = 0;
        degree = degree % 360;
        if (degree < 0)
            degree = 360 + degree;//將角度轉換到0-360度之間
        double ang = Math.toRadians(degree);//將角度轉為弧度

        /**
         *確定旋轉后的圖象的高度和寬度
         */

        if (degree == 180 || degree == 0 || degree == 360) {
            w = iw;
            h = ih;
        } else if (degree == 90 || degree == 270) {
            w = ih;
            h = iw;
        } else {
            int d = iw + ih;
            w = (int) (d * Math.abs(Math.cos(ang)));
            h = (int) (d * Math.abs(Math.sin(ang)));
        }

        x = (w / 2) - (iw / 2);//確定原點坐標
        y = (h / 2) - (ih / 2);
        BufferedImage rotatedImage = new BufferedImage(w, h, image.getType());
        Graphics2D gs = (Graphics2D) rotatedImage.getGraphics();
        if (bgcolor == null) {
            rotatedImage = gs.getDeviceConfiguration().createCompatibleImage(w, h, Transparency.TRANSLUCENT);
        } else {
            gs.setColor(bgcolor);
            gs.fillRect(0, 0, w, h);//以給定顏色繪制旋轉后圖片的背景
        }

        AffineTransform at = new AffineTransform();
        at.rotate(ang, w / 2, h / 2);//旋轉圖象
        at.translate(x, y);
        AffineTransformOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        op.filter(image, rotatedImage);
        image = rotatedImage;

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(byteOut);
        ImageIO.write(image, "png", imageOut);
        return new ByteArrayInputStream(byteOut.toByteArray());
    }


免責聲明!

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



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