Use Jquery+php+mysql to capture and browse photos online

Source: Internet
Author: User
Tags php and mysql jquery library


This article uses the example to describe how to use jquery and PHP and MySQL combination, to achieve the web version of online photo, upload, display browsing function, Ajax interactive technology throughout this article, so the reader of this article is very familiar with jquery and its plug-in use and javscript related knowledge, Knowledge of PHP and MySQL.

This article is based on the site helloweba.com two articles, one is used for online photography: javascript+php to achieve the online photo function, another is used to browse photos: FancyBox rich pop-up layer effect. If you are not familiar with online photography and FancyBox, you can refer to these two articles first.

Html

First, we're going to set up a home page index.html to show the latest uploads, we use jquery to get the latest photos, so this is an HTML page, no PHP tags, and of course, an HTML structure for capturing and uploading the interaction.

<p id= "main" style= "width:90%" >    <p id= "Photos" ></p>        <p id= "Camera" >        <p id= " Cam "></p>        <p id=" webcam "></p>        <p id=" Buttons ">           <p class=" Button_pane "id = "Shoot" >             <a id= "Btn_shoot" href= "class=" Btn_blue "> Take photos </a>           </p>           <p class=" Button_pane hidden "id=" upload ">             <a id=" Btn_cancel "href=" "class=" Btn_blue "> Cancel </a> <a id=" Btn_ Upload "href=" "              class=" Btn_green "> Uploads </a>           </p>        </p>    </p> </p >

We have added the above HTML code to the body, which #photos used to load the photos showing the latest uploads,#camera to load the camera module, including the call camera Flash component webcam, as well as the photo and upload buttons.

In addition, we also need to load the necessary JS files in the index.html, including the jquery library, the FancyBox plugin, the Flash camera component: Webcam.js and This example combines the script.js required for various operations.

<link rel= "stylesheet" type= "Text/css" href= "Fancybox/jquery.fancybox-1.3.4.css"/> <script type= "text/ JavaScript "src=" Http://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

To give you a pretty good front-end interface, we used CSS3 to achieve some shading, fillet, and transparency effects, see:

#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); -webkit-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}

This way you will see a camera button directly below the page when you preview the index.html, which is collapsed by default.

What we'll do next is use jquery: Call the camera component by clicking the camera button below the page, and complete the action required to take pictures, cancel, and upload.

Jquery

All of this interactive action required by JS we are written in the Script.js file. First of all, we need to load the camera component webcam.js, about the webcam call, you can look at this site article: javascript+php to achieve the online camera function. The calling method is as follows:

Script.js-part 1

$ (function () {     webcam.set_swf_url (' js/webcam.swf ');//load the Flash Camera component path     webcam.set_api_url (' upload.php ');    Upload a photo of PHP back-end Processing file     webcam.set_quality (+);                Set the image quality     Webcam.set_shutter_sound (true, ' Js/shutter.mp3 ');//Set the camera sound, the photo will emit "click" Sound      var cam = $ ("#webcam");     Cam.html (         webcam.get_html (Cam.width (), Cam.height ())  //loading the camera assembly in #webcam     );

At this point, the load camera effect is not visible because #camera is collapsed by default and continues to include the following code in Script.js:

Script.js-part 2

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

When you click the camera button just below the page, the default collapsed camera area expands, and if your machine is equipped with a camera, the camera assembly is loaded for camera.

Next, click "Take Photo" to complete the photo function, click "Cancel" to cancel the photos you just took, click "Upload" to upload the photos to the server.

Script.js-part 3

Photo $ ("#btn_shoot"). Click (function () {     webcam.freeze ();  Freeze webcam, the camera stops working for     $ ("#shoot"). Hide ();//Hidden camera button     $ ("#upload"). Show ();//display Cancel and upload button     return false;});  Cancel photo $ (' #btn_cancel '). Click (function () {     webcam.reset ();  Reset webcam, the camera re-work     $ ("#shoot"). Show ();//Display the photo button     $ ("#upload"). Hide ();//suppress Cancel and upload button     return false;});  Upload photo $ (' #btn_upload '). Click (function () {     webcam.upload ();//Upload     webcam.reset ();//reset webcam, Camera re-working     $ ("#shoot"). Show ();//Display the photo button     $ ("#upload"). Hide ();//suppress Cancel and upload button     return false;});

Click on the "Upload" button, the photos will be submitted to the background of PHP processing, PHP to name and save the photos to the storage operation, see how PHP operation upload photos.

Php

upload.php do things: Get uploaded Photos, naming, judging whether legitimate pictures, generating thumbnails, saving, writing to the database, returning JSON information to the front end.

$folder = ' uploads/'; Upload Photo save path $filename = Date (' Ymdhis '). Rand ().  JPG ';  Named photo name $original = $folder. $filename; $input = file_get_contents (' php://input ');   if (MD5 ($input) = = ' 7d4df9cc423720b7f1f3d672b89362be ') {exit; If you are uploading a blank photo, terminate the program} $result = File_put_contents ($original, $input);     if (! $result) {echo ' {"error": 1, "message": "File directory not writable";} '; Exit } $info = getimagesize ($original);     if ($info [' MIME ']! = ' Image/jpeg ') {//If the type is not a picture, delete unlink ($original); Exit }//Generate thumbnail $origImage = Imagecreatefromjpeg ($original);  $newImage = Imagecreatetruecolor (154,110);  Thumbnail size 154x110 imagecopyresampled ($newImage, $origImage, 0,0,0,0,154,110,520,370);  Imagejpeg ($newImage, ' Uploads/small_ '. $filename); Write Database include_once (' connect.php '); $time = Mktime (); $sql = "INSERT INTO Photobooth (pic,uploadtime) VALUES (' $filename ', ' $time ')"; $res = mysql_query ($sql); if ($res) {//Output JSON information echo ' {"status": 1, "message": "success!", "filename": "'. $filename. '} ';} else{echo ' {' Error": 1," "Message": "Sorry,something goes wrong."; }

After upload.php completes the photo upload, it will eventually return the JSON-formatted data to the front-end camera component webcam call, and now we're back to script.js.

Jquery

Webcam through the Set_hook method to capture the background php return information, oncomplete that the upload is complete, onerror is wrong to make a mistake.

Script.js-part 4

webcam.set_hook (' OnComplete ', function (msg) {msg = $.parsejson (msg);//parsing JSON     if (msg.error) {alert (msg.message);         } else {var pic = ' <a rel= "group" href= "uploads/' +msg.filename+ '" ></a> '; $ ("#photos"). Prepend (pic);  Insert the acquired photo information into the #photo of index.html Initfancybox ();  Call the FancyBox Plugin}});  Webcam.set_hook (' OnError ', function (e) {cam.html (e);}); Call FancyBox function Initfancybox () {$ ("A[rel=group]"). FancyBox ({' Transitionin ': ' Elastic ', ' tra Nsitionout ': ' Elastic ', ' cyclic ': true}); }

After uploading successfully, the photos will be inserted into the element #photos dynamically by the above JS code, and the FancyBox plugin can be called simultaneously. At this point, clicking on the photo you just uploaded will render the FancyBox pop-up layer effect. Note that dynamically generated elements must be called by the Initfancybox () function in the code above, and not directly through FancyBox (), otherwise there will be no pop-up effect.

Next, script.js need to do one more thing: dynamically load the latest photos, show on the page, we use the jquery. Getjson () method to complete the AJAX request.

Script.js-part 5

function Loadpic () {     $.getjson ("getpic.php", function (JSON) {         if (JSON) {            $.each (json,function (Index, Array) {//looping JSON data                var pic = ' <a rel= "group" href= "uploads/' +array[' pic ']+ '" >                </a> ';                $ ("#photos"). Prepend (pic);             });         Initfancybox (); Call the FancyBox plugin     }); }  loadpic ();

The function loadpic () sends a GET request to the server getpic.php, parses the returned JSON data, dynamically inserts the photo information into the element #photos , and invokes the FancyBox plug-in, and then Don't forget to call Loadpic () after the page loads.

Php

Finally, the background getpic.php gets the uploaded image from the database and returns the JSON to the front end.

Include_once ("connect.php"); Connect database//Query data table The latest 50 Records $query = mysql_query ("Select pic from photobooth ORDER BY id DESC limit 50"); while ($row =mysql_fetch_array ($query)) {     $arr [] = Array (' pic ' =        $row [' pic ']     );//output JSON data echo Json_ Encode ($arr);

Finally, attach the data photobooth structure:

CREATE TABLE ' photobooth ' (   ' id ' int (one) not null auto_increment,   ' pic ' varchar () ' is not null,   ' Uploadtime ' in T (Ten) not NULL,   PRIMARY KEY  (' id ')) engine=myisam  DEFAULT Charset=utf8;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.