使用html 5画布将图像裁剪为固定的宽度和高度比例,而无需在表单提交之前将图像上载到服务器

时间:2017-04-20 11:42:36

标签: javascript php jquery html5

我有一个表单,用于从多个文本字段中收集数据,并且在同一表单上还有一个用于选择图像的输入文件字段。

我已编写代码将文本字段中的信息插入数据库,同时调整输入字段的图像大小并将其存储在服务器上的文件夹中,并将文件名存储在数据库中。同时创建一个图像缩略图,用于访问者看到的网站前端。

现在的问题是,图像被调整为固定宽度,但调整到固定高度意味着图像要么缩小为肖像图像要么缩放为横向图像。我想使用html 5画布来指定我想要的图像区域,我已经阅读了大量的样本,但他们在裁剪后立即裁剪并上传图像。或者他们在裁剪之前上传。

我想要做的是让输入字段选择图像,用户立即选择从图像中裁剪所需的区域。然后他可以填写其他表单字段,然后当他点击提交按钮时,所有表单字段都会被处理。

我想要存档的示例可以在此链接的表单示例中看到 http://codecanyon.stbeets.nl/

非常需要任何帮助。下面是我没有裁剪的工作代码:

Php部分:

<?php

session_start();

function getExtension($str) {

         $i = strrpos($str,".");
         if (!$i) { return ""; } 

         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

 define ("MAX_SIZE","2048");
    $errors=0;

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if (isset($_POST['login'])) {
    //get form details and check for sql injections and disable them
    $ptitle = mysqli_real_escape_string($connKriticx, $_POST['title']);
    $ptitle = stripslashes($ptitle);
    $pdetail1 = mysqli_real_escape_string($connKriticx, $_POST['detailsec1']);
    $pdetail1 = str_ireplace('\r\n', '', $pdetail1);
    $pphoto1 = $_FILES["photo1"]["name"];
    $uploadedfile = $_FILES['photo1']['tmp_name'];
    $pphotocredit1 = mysqli_real_escape_string($connKriticx, $_POST['photocredit1']);
    $pphotocredit1 = stripslashes($pphotocredit1);


    $query_Admipdetails = "SELECT * FROM admin WHERE email = '" . $_SESSION['User'] . "' LIMIT 1";
    $result_Admipdetails = mysqli_query($connKriticx, $query_Admipdetails);
    $row_Admipdetails = mysqli_fetch_assoc($result_Admipdetails);
    $totalRows_Admipdetails = mysqli_num_rows($result_Admipdetails);

    $userFirstname = $_SESSION["FirstName"];
    $userLastname = $_SESSION["LastName"];


    $pauthor = $userFirstname." ".$userLastname;


    if ($pphoto1){

        $filename = mysqli_real_escape_string($connKriticx, $_FILES['photo1']['name']);
        $extension = getExtension($filename);
        $extension = strtolower($extension);

        // Check if file was uploaded
        if(!isset($_FILES['photo1']) || !is_uploaded_file($_FILES['photo1']['tmp_name'])){
            exit('No file uploaded or Your image has exceeded the size limit of 2Mb. Click the back button on your browser to re-enter the right size of image.');
        }
        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
        {
            echo ' Unknown Image extension ';
            $errors=1;
        }
        else
        {
            $size=filesize($_FILES['photo1']['tmp_name']);

            if ($size > MAX_SIZE*1024)
            {
                echo "Your image has exceeded the size limit";
                $errors=1;
            }

            if($extension=="jpg" || $extension=="jpeg" )
            {
                $uploadedfile = $_FILES['photo1']['tmp_name'];
                $src = imagecreatefromjpeg($uploadedfile);
            }
            else if($extension=="png")
            {
                $uploadedfile = $_FILES['photo1']['tmp_name'];
                $src = imagecreatefrompng($uploadedfile);
            }
            else 
            {
                $src = imagecreatefromgif($uploadedfile);
            }

            list($width,$height)=getimagesize($uploadedfile);



            if ($width > 900) {

            $newwidth=900;  
            $newheight=($height/$width)*$newwidth;
            $tmp=imagecreatetruecolor($newwidth,$newheight);

            imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

            $thumbnewwidth=290;
            $thumbnewheight=($height/$width)*$thumbnewwidth;
            $thumbtmp=imagecreatetruecolor($thumbnewwidth,$thumbnewheight);

            imagecopyresampled($thumbtmp,$src,0,0,0,0,$thumbnewwidth,$thumbnewheight,$width,$height);
            }else{

            $tmp=imagecreatetruecolor($width,$height);      
            imagecopyresampled($tmp,$src,0,0,0,0,$width,$height,$width,$height);

            $thumbnewwidth=290;
            $thumbnewheight=($height/$width)*$thumbnewwidth;
            $thumbtmp=imagecreatetruecolor($thumbnewwidth,$thumbnewheight);

            imagecopyresampled($thumbtmp,$src,0,0,0,0,$thumbnewwidth,$thumbnewheight,$width,$height);
            }

            $set['photo1'] = "'" . $pphoto1 . "'";      
            $kaboom1 = explode(".", $pphoto1);
            $pixExt1 = end($kaboom1);
            $photo1= rand()."_".time().".".$pixExt1;

            $target1 = "../postsimages/". $photo1;
            $thumbtarget1 = "../postsimages/thumbs/". $photo1;

            imagejpeg($tmp,$target1,100);
            imagejpeg($thumbtmp,$thumbtarget1,75);

            imagedestroy($src);
            imagedestroy($tmp);
            imagedestroy($thumbtmp);
        }
    }

    if ((isset($_POST["form_insert"])) && ($_POST["form_insert"] == "adpostsadd")) {

        date_default_timezone_set('Africa/Lagos');
        $date = date('Y-m-d H:i:s');

        $stmt = $connKriticx->prepare("INSERT INTO posts (ptitle, pauthor, pdetail1, pphoto1, pphotocredit1, pdate) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param('ssssss', $ptitle, $pauthor, $pdetail1, $photo1, $pphotocredit1, $date);
        $results = $stmt->execute();
        $stmt->close();

        if($results){
            $updateGoTo = "confirm.php"; 
            $errorGoTo = "error.php";
            if (isset($_SERVER['QUERY_STRING'])) {
                $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
                $updateGoTo .= $_SERVER['QUERY_STRING'];
            }
            header("Location: ". $updateGoTo);
        }else{
                header("Location: ". $errorGoTo);
        }
    }
}
?>

html表单:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>.:: Posts ::.</title>
<link href="css/admin.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.11.0.min.js"></script>
</head>

<body>
    <div id="headercont"><?php include('header.php'); ?></div>
    <div id="wrapper">
        <div class="clear"></div>
        <div id="bodycont">
            <div class="subheadercont">POSTS</div>
            <div class="subbodycont">
                <div class="clear"></div>
                <form method="POST" id="adpostsadd" autocomplete="on" action="<?php echo $editFormAction; ?>" name="adpostsadd" enctype="multipart/form-data">
                    <div class="h1">Title:</div>
                    <div class="clear"></div>
                    <div class="input-field-login2"><input name="title" type="text" required class="std_textbox2" id="title" placeholder="Enter Title" tabindex="1"></div>
                    <div class="clear"></div>
                    <div class="h1">Detail:</div>
                    <div class="clear"></div>
                    <div class="std_textbox2"><textarea name="detailsec1" cols="120" rows="6" required class="input-field-textarea" id="detailsec1" placeholder="Enter Detail" tabindex="1" type="text"></textarea></div>
                    <div class="clear"></div>                    
                    <div class="h1">Select Photo:</div>
                    <input type="hidden" name="MAX_FILE_SIZE" value="2097152" />
                    <input name="photo1" type="file" id="photo1" size="26"/>
                    Must not be more than 2Mb in size!!!
                    <div class="clear"></div>
                    <div class="h1">Photo Credit:</div>
                    <div class="clear"></div>
                    <div class="input-field-login2"><input name="pphotocredit1" type="text" class="std_textbox2" id="pphotocredit1" placeholder="Enter Photo Credit1" tabindex="1"></div>
                    <div class="clear"></div>
                    <div class="text2">
                    <div style="width: 285px;">
                      <div class="login-btn3">
                        <button name="login" type="submit" id="login_submit" tabindex="3">Add Post</button>
                      </div>
                    </div>
                    <div class="clear"></div>
                    <div id="divline"></div>
                    <div class="clear"></div>
                    <div class="text2"><a href="javascript:history.go(-1)">&laquo; Back</a></div>
                    <div class="clear"></div>  
                </div>
                    <input type="hidden" name="form_insert" value="adpostsadd">
                </form>
                <div class="clear"></div>
            </div>
            <div class="clear"></div>            
        </div>
    </div>
</body>
</html>

0 个答案:

没有答案