みんなを率いて一緒にThinkPHP統合jcropピクチャーのアップロードの裁断プレビューの例をします


技術グループでPHP画像に裁断をアップロードしてプレビューする例を聞く人がよくいます.今日はちょうど時間があって、自分で1つ作って、同時に方法を公表して、みんなに理解させることができて、ThinkPHP+jcropでこの例をする方法をマスターします.まずjcropを降りて、URL:http://deepliquid.com/content/Jcrop_Download.html
   ダウンロードが完了したら、js、demo、cssなどのフォルダがあります.demoには例があります.まずソースコードを見てみることをお勧めします.残りは、私と一緒にこの例を作ってください.
   1.ThinkPHPをダウンロードし、新規プロジェクトを作成し、プロジェクトディレクトリを生成する
   2.TplでIndex/index.htmlを新規作成
コードは次のとおりです.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>    </title>
 <script>
     function setFile(f1){
        document.frm.logoImg.value=f1;
     }
    </script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td height="45" align="center" valign="middle">
        <form action="#" method="post"  name="frm">         
              <input name="logoImg" id="logoImg"   type="text" size="30"/>
             <label style="cursor:hand" onClick="window.open('__URL__/upimg','    ','height=600,width=800,top=200,left=200')">    </label><br/>
        </form>
    </td>
  </tr>
</table>
</body>
</html>

これはアップロードで、アップロード画像をクリックすると、画像の裁断をアップロードするためのウィンドウがポップアップされます.Tpl/index/の下にupimg.htmlを新規作成
コードは次のとおりです.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>    </title>
<script language="javascript">
    function $(id){
        return document.getElementById(id);
    }
    function ok(){
         $("logoimg").src = $("filename").value;
     }
</script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td height="45" align="center" valign="middle">
        <form action="__URL__/uploadf?submit=1" method="post" enctype="multipart/form-data" name="form1">         
            <input type="file" name="filename" id="filename" onchange="ok()">
            <!-- MAX_FILE_SIZE must precede the file input field -->
            <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
            <input type="submit" name="Submit" value="  ">
        </form>
    </td>
  </tr>
</table>
</body>
</html>

私はTPが持っているファイルのアップロードクラスを使っていません.もしみんなが必要なら、変更することができます.以上は主にアップロードファイルのウィンドウをポップアップします.このウィンドウでは、ファイルのアップロード、裁断などの操作が完了します.クリックしてIndex/uploadfに送信
Index/uploadfコードは次のとおりです.
$path = "uploadfiles/";         //      
                if (! file_exists ( $path )) {
                    mkdir ( "$path", 0700 );
                }
                $tp = array (
                        "image/gif",
                        "image/jpeg",
                        "image/png",
                        "image/jpg"
                );
                                                                                                                                                                                                                                             
                if (! in_array ( $_FILES ["filename"] ["type"], $tp )) {
                    echo "    ";
                    exit ();
                } // END IF
                                                                                                                                                                                                                                             
                if ($_FILES ["filename"] ["name"]) {
                    $file1 = $_FILES ["filename"] ["name"];
                    $file2 = $path . time () . $file1;
                    $flag = 1;
                }
                                                                                                                                                                                                                                             
                if ($flag)
                    $result = move_uploaded_file ( $_FILES ["filename"] ["tmp_name"], $file2 );
                if ($result) {
                                                                                                                                                                                                                                         
                    $this->assign('filename',$file2);
                    $this->display();
                }

アップロードが完了するとuploadf.htmlに直接ジャンプします.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script src="__STYLE__/js/jquery.min.js"></script>
<script src="__STYLE__/js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="__STYLE__/css/main.css" type="text/css" />
<link rel="stylesheet" href="__STYLE__/css/demos.css" type="text/css" />
<link rel="stylesheet" href="__STYLE__/css/jquery.Jcrop.css" type="text/css" />
<script language='javascript'>
    jQuery(function($) {
        var jcrop_api, boundx, boundy,
        $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'),
        xsize = $pcnt.width(), ysize = $pcnt.height();
        console.log('init', [ xsize, ysize ]);
        $('#target').Jcrop({
            onChange : updatePreview,
            onSelect : updatePreview,
            aspectRatio : xsize / ysize
        }, function() {
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            $preview.appendTo(jcrop_api.ui.holder);
        });
        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                $pimg.css({
                    width : Math.round(rx * boundx) + 'px',
                    height : Math.round(ry * boundy) + 'px',
                    marginLeft : '-' + Math.round(rx * c.x) + 'px',
                    marginTop : '-' + Math.round(ry * c.y) + 'px'
                });
                                                                                                                                                                                                                                   
                $('#x').val(c.x);
                $('#y').val(c.y);
                $('#w').val(c.w);
                $('#h').val(c.h);
            }
        }
        ;
        function updateCoords(c){
                                                                                                                                                                                                                                   
            };
                                                                                                                                                                                                                               
    });
</script>
<style type="text/css">
.jcrop-holder #preview-pane {
    display: block;
    position: absolute;
    z-index: 2000;
    top: 10px;
    right: -240px;
    padding: 6px;
    border: 1px rgba(0, 0, 0, .4) solid;
    background-color: white;
    -webkit-border-radius: 6px;
    -moz-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
    box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}
#preview-pane .preview-container {
    width: 170px;
    height: 250px;
    overflow: hidden;
}
</style>
<body>
    <div class="container">
        <div class="row">
            <div class="span12">
                <div class="jc-demo-box">
                    <img src="__ROOT__/{$filename}" id="target" alt="[Jcrop Example]" />
                    <div id="preview-pane">
                        <div class="preview-container">
                            <img src="__ROOT__/{$filename}" class="jcrop-preview"
                                alt="Preview" />
                        </div>
                    </div>
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
    <form action="__URL__/uploadf?submit=cut" method="post" onsubmit="return checkCoords();">
            <input type="hidden" id="x" name="x" />
            <input type="hidden" id="y" name="y" />
            <input type="hidden" id="w" name="w" />
            <input type="hidden" id="h" name="h" />
            <input type="hidden" name="filename" value="{$filename}">
            <input type="submit" value="Crop Image" />
        </form>
    <!--     <img src="__ROOT__/{$filename}" alt="" /> -->
</body>
</html>

ここのコードは長いので、ゆっくり説明してください.私が直接コピーしたjcrop demoのtutorial 3.htmlは、彼自身が必要とするjs、cssをロードします.内
#preview-pane .preview-container {
    width: 170px;
    height: 250px;
    overflow: hidden;
}

この部分CSSは出てくる裁断枠の割合に影響します.およびプレビューのサイズ.
$('#target').Jcrop({
            onChange : updatePreview,
            onSelect : updatePreview,
            aspectRatio : xsize / ysize
        }, function() {
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            jcrop_api = this;
            $preview.appendTo(jcrop_api.ui.holder);
        });

onChangeとonSelectでは、裁断時に実行するjsコードを意味しますが、正直、私のjsとjqのレベルはゴミです.だから放っておいた.
function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                $pimg.css({
                    width : Math.round(rx * boundx) + 'px',
                    height : Math.round(ry * boundy) + 'px',
                    marginLeft : '-' + Math.round(rx * c.x) + 'px',
                    marginTop : '-' + Math.round(ry * c.y) + 'px'
                });
                                                                                                                                                                
                $('#x').val(c.x);
                $('#y').val(c.y);
                $('#w').val(c.w);
                $('#h').val(c.h);
            }
        }
        ;

この後、私は自分でformフォームに付与する付与値を追加しました.phpに提出して裁断作業を完了します
uploadfにコミットするには、自分で画像カットのクラスを書くことができます.
<?php
class Imgshot {
    private $filename;
    private $ext;
    private $x;
    private $y;
    private $x1;
    private $y1;
    private $width = 170;
    private $height = 250;
    private $jpeg_quality = 90;
    /**
     *    
     */
    public function __construct() {
//      log_message ( 'debug', "Img_shot Class Initialized" );
    }
    /**
     *        
     *
     * @param
     *          filename        
     * @param
     *          width     
     * @param
     *          height     
     * @param
     *          x    1
     * @param
     *          y    1
     * @param
     *          x1    1
     * @param
     *          y1    2
     *        
     */
    public function initialize($filename, $x, $y, $x1, $y1) {
        if (file_exists ( $filename )) {
            $this->filename = $filename;
            $pathinfo = pathinfo ( $filename );
            $this->ext = $pathinfo ['extension'];
        } else {
            $e = new Exception ( 'the file is not exists!', 1050 );
            throw $e;
        }
        $this->x = $x;
        $this->y = $y;
        $this->x1 = $x1;
        $this->y1 = $y1;
    }
    /**
     *     
     *        ,       
     */
    public function generate_shot() {
        switch ($this->ext) {
            case 'jpg' :
                return $this->generate_jpg ();
                break;
            case 'png' :
                return $this->generate_png ();
                break;
            case 'gif' :
                return $this->generate_gif ();
                break;
            default :
                return false;
        }
    }
    /**
     *            
     */
    private function get_shot_name() {
        $pathinfo = pathinfo ( $this->filename );
        $fileinfo = explode ( '.', $pathinfo ['basename'] );
        $filename = $fileinfo [0] . '_small.' . $this->ext;
        return 'uploadfiles/'.$filename;
    }
    /**
     *   jpg     
     */
    private function generate_jpg() {
        $shot_name = $this->get_shot_name ();
        $img_r = imagecreatefromjpeg ( $this->filename );
        $dst_r = ImageCreateTrueColor ( $this->width, $this->height );
                                                                                                     
        imagecopyresampled ( $dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1 );
        imagejpeg ( $dst_r, $shot_name, $this->jpeg_quality );
        return $shot_name;
    }
    /**
     *   gif     
     */
    private function generate_gif() {
        $shot_name = $this->get_shot_name ();
        $img_r = imagecreatefromgif ( $this->filename );
        $dst_r = ImageCreateTrueColor ( $this->width, $this->height );
                                                                                                     
        imagecopyresampled ( $dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1 );
        imagegif ( $dst_r, $shot_name );
        return $shot_name;
    }
    /**
     *   png     
     */
    private function generate_png() {
        $shot_name = $this->get_shot_name ();
        $img_r = imagecreatefrompng ( $this->filename );
        $dst_r = ImageCreateTrueColor ( $this->width, $this->height );
                                                                                                     
        imagecopyresampled ( $dst_r, $img_r, 0, 0, $this->x, $this->y, $this->width, $this->height, $this->x1, $this->y1 );
        imagepng ( $dst_r, $shot_name );
        return $shot_name;
    }
}
?>

これは私がネット上でdownしたのです.~自分で書いていないので、自分で需要に応じて拡張することができます.
裁断操作:
    $filename=$this->cut();
                echo "<script language='javascript'>";
                echo "alert(\"    !\");";
                echo "</script>";
                echo ("<input type=\"button\" name=\"Submit\" value=\"  \" onClick=\"window.opener.setFile('" .$filename. "');window.close();\">");
                echo '<img src="'.__ROOT__.'/'.$filename.'" alt="" />';
//     
    function cut(){
        import('ORG.Net.Imgshot');
        $imgshot=new Imgshot();
        $imgshot->initialize(SITE_PATH.'/'.$_REQUEST['filename'], $_REQUEST['x'], $_REQUEST['y'], $_REQUEST['x']+$_REQUEST['w'], $_REQUEST['y']+$_REQUEST['h']);
        $filename=$imgshot->generate_shot();
        return $filename;
    }

完了すると、最後にカットされた画像が直接echoで表示され、確定ボタンもあり、確定をクリックすると、カットされた画像のアドレスが最初のinput[type="text"]に戻ります.全体の例は私はまだ完備していないので、みんなは必要に応じて自分で理解して完備することができます.はい、できない友达はグループを追加することができます:252799167私に聞いてください.全体の例は私はすでにThinkPHPの公式サイトに発表して、みんなはダウンロードすることができます.
http://www.thinkphp.cn/topic/9154.html