Allows you to take photos online and browse photos online based on jQuery + PHP + Mysql,

Source: Internet
Author: User
Tags php and mysql

Allows you to take photos online and browse photos online based on jQuery + PHP + Mysql,

This document uses examples to illustrate how to use jQuery in combination with PHP and Mysql to enable the WEB version to take photos, upload, display, and browse online. ajax Interaction Technology runs through the beginning and end of this article, therefore, the readers in this article must be familiar with jQuery and its plug-ins and javscript knowledge, and have knowledge about PHP and Mysql.


Click hereDownload source code

HTML

First, we need to create a main page index.html to display the latest uploaded photos. We use jQuery to obtain the latest photos. Therefore, this is an HTML page without the PHP tag, of course, you also need to create an HTML structure that is required for photo taking and upload interaction.


<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"> Take a picture </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 added the above html code between the body, where #photos is used to load the latest uploaded photos; #camera is used to load the camera module, including calling the camera flash component webcam, as well as taking pictures and uploading buttons.
In addition, we also need to load the necessary js files in index.html, including jQuery library, fancybox plug-in, flash camera component: webcam.js and script.js required by this example to combine 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 show you a pretty beautiful front-end interface, we used css3 to achieve some shadows, rounded corners and transparency effects, please 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, when you preview index.html, you will find a camera button directly below the page, which is collapsed by default.
The next thing we need to do is to use jQuery to achieve: by clicking the camera button directly below the page, call the camera component, and complete the actions required to take pictures, cancel and upload.
jQuery
The js required for all these interactive actions are written in the script.js file. First of all, we need to load the camera component webcam.js. For the call of webcam, you can read the article on this site: Javascript + PHP to realize the online camera function. The calling method is as follows:
script.js-Part 1
$ (function () {
 webcam.set_swf_url ('js / webcam.swf'); // The path to load the flash camera component
 webcam.set_api_url ('upload.php'); // PHP backend processing file for uploading photos
 webcam.set_quality (80); // Set the image quality
 webcam.set_shutter_sound (true, 'js / shutter.mp3'); // Set the photo sound, there will be a "click" sound
 var cam = $ ("# webcam");
 cam.html (
 webcam.get_html (cam.width (), cam.height ()) // Load the camera component in #webcam
 );

At this time, you can't see the effect of loading the camera, because #camera is folded by default, continue to add the following code to 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 will expand upwards. At this time, if your machine is equipped with a camera, the camera component will be loaded for camera shooting.
Next, click "Take Photo" to complete the photo function, click "Cancel" to cancel the photo just taken, click "Upload" to upload the photo taken to the server.
script.js-Part 3
// Take a picture
$ ("# btn_shoot"). click (function () {
 webcam.freeze (); // Freeze the webcam, the camera stops working
 $ ("# shoot"). hide (); // Hide the camera button
 $ ("# upload"). show (); // Show cancel and upload buttons
 return false;
});
// Cancel the photo
$ ('# btn_cancel'). click (function () {
 webcam.reset (); // Reset the webcam, the camera works again
 $ ("# shoot"). show (); // Show camera button
 $ ("# upload"). hide (); // Hide cancel and upload buttons
 return false;
});
//upload photos 
$ ('# btn_upload'). click (function () {
 webcam.upload (); // Upload
 webcam.reset (); // Reset the webcam, the camera works again
 $ ("# shoot"). show (); // Show camera button
 $ ("# upload"). hide (); // Hide cancel and upload buttons
 return false;
});

After clicking the "Upload" button, the photos taken will be submitted to the background PHP for processing. PHP will name the photos and save them into the database. Please see how PHP uploads photos.
PHP
What upload.php does is: get the uploaded photos, name them, determine whether the pictures are legal, generate thumbnails, save them, write to the database, and return JSON information to the front end.
$ folder = 'uploads /'; // Save path for uploaded photos
$ filename = date ('YmdHis'). rand (). '. jpg'; // Name the photo name
$ original = $ folder. $ filename;
$ input = file_get_contents ('php: // input');
if (md5 ($ input) == '7d4df9cc423720b7f1f3d672b89362be') {
exit; // If you upload a blank photo, terminate the program
}
$ result = file_put_contents ($ original, $ input);
if (! $ result) {
echo '{"error": 1, "message": "File directory cannot be written";}';
exit;
}
$ info = getimagesize ($ original);
if ($ info ['mime']! = 'image / jpeg') {// If the type is not an image, 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 to the database
include_once ('connect.php');
$ time = mktime ();
$ sql = "insert into photobooth (pic, uptime) 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 format data to the front-end camera component webcam call, now we return to script.js.
jQuery
Webcam captures the background PHP return information through the set_hook method, onComplete indicates that the upload is completed, and onError indicates that something has been wrong.
script.js-Part 4
webcam.set_hook ('onComplete', function (msg) {
msg = $ .parseJSON (msg); // parse json
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); // Insert the acquired photo information into #photo in index.html
initFancyBox (); // Call fancybox plugin
}
});
webcam.set_hook ('onError', function (e) {
cam.html (e);
});
// Call fancybox
function initFancyBox () {
$ ("a [rel = group]"). fancybox ({
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'cyclic': true
});
}

Explain that after the upload is successful, the photos taken will be dynamically inserted into the element #photos through the above js code, and the fancybox plugin will be called at the same time. At this time, click on the photo you just uploaded, and the fancybox pop-up layer effect will appear. Note that dynamically generated elements must call fancybox through the initFancyBox () function in the above code, not directly through fancybox (), otherwise there will be no pop-up layer effect.
Next, script.js needs to do one more thing: dynamically load the latest photos and display them on the page. We complete the ajax request through jquery's .getJSON () method.
script.js-Part 5

function loadpic () {
 $ .getJSON ("getpic.php", function (json) {
 if (json) {
  $ .each (json, function (index, array) {// Cycle json data
  var pic = '<a rel="group" href="uploads/'+array['pic']+'">
  <img src = "uploads / small _ '+ 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, dynamically inserts the photo information under the element #photos, and calls the fancybox plugin. Then, do n’t forget to call loadpic after the page loads ().
PHP
Finally, the background getpic.php gets the uploaded pictures in the database and returns json to the front end.
include_once ("connect.php"); // Connect to the database
// Query the latest 50 records in the data table
$ 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 (11) NOT NULL auto_increment,
 `pic` varchar (50) NOT NULL,
 `uploadtime` int (10) 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.