Jquery+php+mysql online photos and online browsing

Source: Internet
Author: User
Tags html page json php and php and mysql jquery library

This article demonstrates how to use jquery with PHP and MySQL, the implementation of the web version of online photos, upload, display browsing functions, Ajax interaction technology throughout the whole of this article, so the reader of this article requires a fairly familiar with jquery and its plug-in use and javscript related knowledge, Knowledge of PHP and MySQL related.

The example of this article is based on the site helloweba.com two articles, one is for online photography: javascript+php to achieve 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 both of these articles first.
Html

First, we're going to create a home page index.html to showcase the latest uploaded photos, we use jquery to get the latest photos, so this is an HTML page that doesn't require PHP tags, and of course creates an HTML structure that includes the need to take photos and upload interactions.

<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 "> Photo </a>
</div>
<div class= "Button_pane hidden" id= "Upload" >
<a id= "Btn_cancel" href= "class=" Btn_blue "> Cancel </a> <a id=" btn_upload "href=" "
class= "Btn_green" > Upload </a>
</div>
</div>
</div>
</div>

We have added the above HTML code to the body, where #photos is used to load the latest uploaded photos; #camera用于加载摄像模块, including calling the camera flash component webcam, and taking photos and uploading buttons.

In addition, we also need to load the necessary JS files in the index.html, including the jquery library, FancyBox plug-ins, Flash camera components: 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

In order to give you a pretty good front end interface, we use the CSS3 to achieve some shadow, 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}

In this way you will find a camera button just below the page, which is folded by default, when previewing index.html.

What we're going to do next is use jquery: by clicking the camera button on the bottom of the page, call the camera component and complete the action required to take pictures, cancel and upload.
Jquery

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

Script.js-part 1

$ (function () {
Webcam.set_swf_url (' js/webcam.swf '); The path to load the Flash camera assembly
Webcam.set_api_url (' upload.php '); Upload photos of PHP back-end processing files
Webcam.set_quality (80); Set Image quality
Webcam.set_shutter_sound (True, ' Js/shutter.mp3 '); Set the sound of the camera to make a "click" sound when taking pictures

var cam = $ ("#webcam");
Cam.html (
Webcam.get_html (Cam.width (), Cam.height ())//Loading of camera components in #webcam
);

At this point, you also do not see the load camera effect, because #camera is collapsed by default, continue to add 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 directly below the page, the default folded camera area expands upwards, and if your machine has a camera installed, it will load the camera component for camera.

Next, click "Take a Photo" to complete the photo function, click "Cancel" to cancel the photo 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, Camera stops working
$ ("#shoot"). Hide (); Hide Photo button
$ ("#upload"). Show (); Show Cancel and upload button
return false;
});

Cancel Photo
$ (' #btn_cancel '). Click (function () {
Webcam.reset (); Reset webcam, camera back to work
$ ("#shoot"). Show (); Show Photo button
$ ("#upload"). Hide (); Hide Cancel and upload button
return false;
});

Upload Photos
$ (' #btn_upload '). Click (function () {
Webcam.upload (); Upload
Webcam.reset ()//reset webcam, camera back to work
$ ("#shoot"). Show ()//Display photo button
$ ("#upload"). Hide (); Hide Cancel and upload button
return false;
});

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

The things that upload.php do are: Get uploaded photos, name them, judge whether they are legitimate pictures, generate thumbnails, save, write to the database, and return 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 a blank photo is uploaded, 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 thumbnails
$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);

Writing to the 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 camera component webcam call, and now we're back to script.js.
Jquery

Webcam through the Set_hook method to capture backstage php return information, OnComplete said upload completed, onerror is wrong to make mistakes.

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+ ' >msg.filename+ ' ></a> ';
$ ("#photos"). Prepend (pic); Insert the captured photo information into the #photo of index.html
Initfancybox (); Calling the FancyBox plug-in
}
});

Webcam.set_hook (' OnError ', function (e) {
Cam.html (e);
});

Call FancyBox
function Initfancybox () {
$ ("A[rel=group]"). FancyBox ({
' Transitionin ': ' Elastic ',
' Transitionout ': ' Elastic ',
' Cyclic ': true
});
}

Explain, upload success, the photos will be through the above JS code dynamically inserted into the element #photos, and also call the FancyBox plug-in. At this point, click on the photos just uploaded, will present the FancyBox pop-up layer effect. Note that dynamically generated elements must be called by the Initfancybox () function in the above code, not directly by FancyBox (), otherwise there will be no pop-up effects.

Next, Script.js needs to do one more thing: dynamically loading the latest photos, showing them on the page, we complete the AJAX request through the jquery. Getjson () method.

Script.js-part 5

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

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

Finally, the background getpic.php to get the uploaded images from the database and return JSON to the front end.

Include_once ("connect.php"); Connecting to a database
Query the latest 50 records in a datasheet
$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, the data photobooth structure is attached:

CREATE TABLE ' Photobooth ' (
' id ' int (one) not NULL auto_increment,
' pic ' varchar not NULL,
' Uploadtime ' int (a) 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.