DIV CSS 佈局教程網

jQuery+PHP+MySQL 實作線上拍照、上傳與瀏覽
編輯:關於JavaScript     

本文把「線上拍照」這個需求從頭到尾做一遍:前端用 jQuery 呼叫 Flash 攝像元件取得畫面,拍照後預覽,確認再按上傳;後端用 PHP 接收二進位資料、命名存盤、生成縮圖並寫入 MySQL;最後用 getJSON 拉出最新照片,搭配 fancybox 做彈出式瀏覽。整條流程以 Ajax 貫穿。閱讀前請先具備 jQuery 與其外掛的使用經驗,以及 PHP、MySQL 的基礎。

一、HTML 結構

首頁 index.html 只負責展示,資料全靠 jQuery 撈取,所以不必寫 PHP。它包含兩個主要區域:#photos 放最新照片,#camera 放攝像模組與操作按鈕。

 <div id="main" style="width:90%">
 <div id="photos"></div>
 <div id="camera">
  <div id="cam"></div>
  <div id="webcam"></div>
  <div id="buttons">
   <div class="button_pane" id="shoot">
    <a id="btn_shoot" href="" class="btn_blue">拍照</a>
   </div>
   <div class="button_pane hidden" id="upload">
    <a id="btn_cancel" href="" class="btn_blue">取消</a>
    <a id="btn_upload" href="" class="btn_green">上傳</a>
   </div>
  </div>
 </div>
</div>

接著載入四支腳本:jQuery、fancybox 及其樣式、攝像元件 webcam.js,以及本文的 script.js。

 <link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.4.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="js/webcam.js"></script>
<script type="text/javascript" src="js/script.js"></script>

二、CSS 樣式

介面效果大量用到 CSS3 的陰影、圓角與透明度:

 #photos{width:80%; margin:40px auto}
 #photos:hover a{opacity:0.5}
 #photos a:hover{opacity:1}
 #camera{
   width:598px; height:525px; position:fixed; bottom:-466px; left:50%;
   margin-left:-300px; border:1px solid #f0f0f0;
   background:url(images/cam_bg.jpg) repeat-y;
   -moz-border-radius:4px 4px 0 0; -webkit-border-radius:4px 4px 0 0; border-radius:4px 4px 0 0;
   -moz-box-shadow:0 0 4px rgba(0,0,0,0.6); box-shadow:0 0 4px rgba(0,0,0,0.6);
 }
 #cam{width:100%; height:66px; display:block; position:absolute; top:0; left:0;
   background:url(images/cam.png) no-repeat center center; cursor:pointer}
 #webcam{width:520px; height:370px; margin:66px auto 22px; line-height:360px;
   background:#ccc; color:#666; text-align:center}
 .button_pane{text-align:center;}
 .btn_blue,.btn_green{width:99px; height:38px; line-height:32px; margin:0 4px; border:none;
   display:inline-block; text-align:center; font-size:14px; color:#fff !important;
   text-shadow:1px 1px 1px #277c9b; background:url(images/buttons.png) no-repeat}
 .btn_green{background:url(images/buttons.png) no-repeat right top; text-shadow:1px 1px 1px #498917;}
 .hidden{display:none}

注意 #camera 的 bottom:-466px:攝像面板平時藏在頁面下方,只露出 66px 高的 #cam 當作把手,點擊後才滑出來。

三、jQuery:載入攝像元件與面板滑出

 $(function(){
    webcam.set_swf_url('js/webcam.swf');       // Flash 攝像元件路徑
    webcam.set_api_url('upload.php');          // 上傳處理的後端
    webcam.set_quality(80);                    // 畫質
    webcam.set_shutter_sound(true, 'js/shutter.mp3');   // 快門聲

    var cam = $("#webcam");
    cam.html( webcam.get_html(cam.width(), cam.height()) );
});

var camera = $("#camera");
var shown = false;
$('#cam').click(function(){
    if(shown){ camera.animate({ bottom:-466 }); }
    else     { camera.animate({ bottom:-5   }); }
    shown = !shown;
});

四、拍照、取消、上傳

 // 拍照
$("#btn_shoot").click(function(){
    webcam.freeze();      // 凍結畫面
    $("#shoot").hide();
    $("#upload").show();
    return false;
});
// 取消,重新取景
$('#btn_cancel').click(function(){
    webcam.reset();
    $("#shoot").show();
    $("#upload").hide();
    return false;
});
// 上傳
$('#btn_upload').click(function(){
    webcam.upload();
    webcam.reset();
    $("#shoot").show();
    $("#upload").hide();
    return false;
});

五、PHP:接收、存盤、寫庫

upload.php 的流程是:讀取原始二進位 → 命名 → 驗證是否為合法 JPEG → 生成 154×110 縮圖 → 寫入 uploads/ → 落庫 → 回傳 JSON。

 $folder = 'uploads/';                        // 上傳目錄
$filename = date('YmdHis').rand().'.jpg';    // 以時間戳+亂數命名
$original = $folder.$filename;

$input = file_get_contents('php://input');
if(md5($input) == '7d4df9cc423720b7f1f3d672b89362be'){ exit; }   // 空白影像直接結束

$result = file_put_contents($original, $input);
if (!$result) {
    echo '{"error":1,"message":"文件目錄不可寫"}';
    exit;
}

$info = getimagesize($original);
if($info['mime'] != 'image/jpeg'){ unlink($original); exit; }   // 非圖片則刪除

// 生成縮圖
$origImage = imagecreatefromjpeg($original);
$newImage  = imagecreatetruecolor(154,110);
imagecopyresampled($newImage, $origImage, 0,0,0,0, 154,110, 520,370);
imagejpeg($newImage, 'uploads/small_'.$filename);

// 寫入資料庫
include_once('connect.php');
$time = mktime();
$sql  = "insert into photobooth (pic,uploadtime) values('$filename','$time')";
$res  = mysql_query($sql);

if($res){
    echo '{"status":1,"message":"Success!","filename":"'.$filename.'"}';
}else{
    echo '{"error":1,"message":"Sorry, something goes wrong."}';
}

六、接收回呼與動態插入

 webcam.set_hook('onComplete', function(msg){
    msg = $.parseJSON(msg);
    if(msg.error){
        alert(msg.message);
    }else{
        var pic = '<a rel="group" href="uploads/'+msg.filename+'">'
                + '<img src="uploads/small_'+msg.filename+'"></a>';
        $("#photos").prepend(pic);
        initFancyBox();     // 必須重新初始化
    }
});
webcam.set_hook('onError', function(e){ cam.html(e); });

function initFancyBox(){
    $("a[rel=group]").fancybox({
        'transitionIn' : 'elastic',
        'transitionOut': 'elastic',
        'cyclic'       : true
    });
}

這裡有個容易踩的坑:動態插入的元素必須重新呼叫 initFancyBox() 綁定,直接寫 fancybox() 對新元素是無效的。

七、載入歷史照片

 function loadpic(){
    $.getJSON("getpic.php", function(json){
        if(json){
            $.each(json, function(index, array){
                var pic = '<a rel="group" href="uploads/'+array['pic']+'">'
                        + '<img src="uploads/small_'+array['pic']+'"></a>';
                $("#photos").prepend(pic);
            });
        }
        initFancyBox();
    });
}
loadpic();
 include_once("connect.php");
// 取最新 50 筆
$query = mysql_query("select pic from photobooth order by id desc limit 50");
while($row = mysql_fetch_array($query)){
    $arr[] = array('pic' => $row['pic']);
}
echo json_encode($arr);

資料表結構:

 CREATE TABLE `photobooth` (
  `id` int(11) NOT NULL auto_increment,
  `pic` varchar(50) NOT NULL,
  `uploadtime` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

八、上線前務必修正的三件事

  • SQL 與檔案安全:範例用字串拼接 SQL,且直接信任上傳的二進位內容。正式環境請改用 PDO prepared statement,並以 getimagesize() 失敗與 move_uploaded_file 的結果作為唯一放行依據,同時限制檔案大小。
  • mysql_* 已移除:mysql_query 在 PHP 7 起不再存在,請改用 mysqli 或 PDO。
  • Flash 已終止支援:webcam.swf 這條路線在現代瀏覽器已不可行。若要重做同樣的功能,請改用 navigator.mediaDevices.getUserMedia() 搭配 <canvas> 取像,再以 toBlob() 上傳,其餘的後端流程與本文完全相同。

把前端換成 getUserMedia、後端換成 PDO,這套架構依然成立且更為安全。希望這個完整範例對你的開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved