I want to capture image from webcam user image that image stored in specified folder and captured image path store into mysql using php. I have an problem with webcam captured image path is not stored in mysql database. so please help me...
<script src="webscript.js"></script>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="webcam.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
var shutter = new Audio();
shutter.autoplay = false;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
Webcam.upload( data_uri, 'upload.php', function(code, text) {
alert(data_uri);
});
} );
}
</script>
<?php
include 'connection.php';
// be aware of file / directory permissions on your server
$newname = move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.date('YmdHis').rand(383,1000).'.jpg');
$query = "INSERT INTO entry(name) VALUES('".$_GET['url']."')";
mysql_query($query)or die(mysql_error());
echo "<script>alert('successfully..');</script>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Javascript Webcam</title>
<link href="font-awesome.min.css" rel="stylesheet"/>
<link href="bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<center>
<div class="row">
<div class="col-md-6">
<h3>Profile Picture</h3>
<div id="my_camera"></div>
<!-- A button for taking snaps -->
<form>
<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div id="results" class="well">Your captured image will appear here...</div>
</div>
</div>
</center>
</body>
</html>
Assuming $mysqli is a successfully connected [new Mysqli] object.
$query = "SELECT * FROM 'database.table' WHERE 'somecolumn'='someval' LIMIT= 5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();
Related
I have sucessfully created a website that used the https://github.com/BossBele/cropzee library.
I have created a HTML form that takes inn a image from the user:
When the user has selected a image the Cropzee.js sucessfully loads and I can rotated/crop the image as expected:
Now I have the button Get Image (as blob / data-url) that gives me a alert box with a base64 image:
<button onclick="alert(cropzeeGetImage('cropzee-input'))">Get Image (as blob / data-url)</button>
I need to somehow send the base64 blob / data-url / image to my backend, I use PHP.
My HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cropzee jQuery PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0;"/>
<!-- jQuery + cropzee.js -->
<script type="text/javascript" src="javascripts/jquery/jquery.min.js"></script>
<script src="javascripts/cropzee/cropzee.js" defer></script>
<!-- //jQuery + cropzee.js -->
<!-- CSS -->
<style>
.image-previewer {
height: 300px;
width: 300px;
display: flex;
border-radius: 10px;
border: 1px solid lightgrey;
}
</style>
<!-- //CSS -->
</head>
<body>
<h1>Upload</h1>
<!-- cropzee upload form -->
<label for="cropzee-input" class="image-previewer" data-cropzee="cropzee-input"></label>
<input id="cropzee-input" type="file" name="cropzee-input" accept="image/*">
<button onclick="alert(cropzeeGetImage('cropzee-input'))">Get Image (as blob / data-url)</button>
<script>
$(document).ready(function(){
if (window.location.href.indexOf("#") > -1) {
window.location = window.location.href.replace('#', '');
}
$("#cropzee-input").cropzee({startSize: [85, 85, '%'],});
});
</script>
<!-- //cropzee upload form -->
</body>
</html>
I have done this working to save the cropped image via Ajax Post to my PHP/MySQL backend.
Put a button to trigger the Ajax Call - like below
`<input type="button" onclick="uploadEx()" value="Upload" />`
Create a from with a hidden input - like below
`<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' type="hidden"/>
</form>`
Now put the Ajax call jQuery - like below
function uploadEx() {
var canvas = document.getElementById("cropzee-input");
var dataURL = canvas.toDataURL("image/jpeg");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
alert('Succesfully uploaded');
} else {
alert('Captured data');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
```
Lastly the PHP file upload_data.php looks like below
`
$upload_dir = "uploaded_files/profile_pictures/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".jpeg";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.'; `
I'm building a chat website and i want to add a sound alert whenever a new message is sent so i can alert other users for new unread messages(i use MySQL for storing messages etc.). I use ajax to get the messages from the database and put them on my chatbox. I tryied every way but it doesn't seen to work idividually on every NEW message. Please help!
That's my index.php
<?php
session_start ();
define('DB_HOST', 'localhost');
define('DB_NAME', '*******');
define('DB_USER','*****');
define('DB_PASSWORD','********');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Chat2Chat!</title>
</head>
<body id="body-color">
<?php
if (! isset ( $_SESSION ['user'] )) {
header ( "Location: sign-in.html" ); // Redirect the user
} else {
?>
<div id="wrapper">
<div id="menu">
<p class="welcome">
Καλωσήρθες, <b><?php echo $_SESSION['user']; ?></b>
</p>
<p class="logout">
<b class="submitmsg" id="exit" href="#">Logout</b>
</p>
<div style="clear: both"></div>
</div>
<div id="chatbox" class="chatbox">
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" autofocus/>
<input class="submitmsg" name="submitmsg" type="submit" id="submitmsg" value="Αποστολή"/>
</form>
</div>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
setInterval ( "get()", 2000 );
});
//jQuery Document
$(document).ready(function(){
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Είσαι σίγουρος πως θέλεις να αποσυνδεθείς;");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
loadLog;
return false;
});
setInterval (loadLog, 2500);
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatbox").html(data);
var scroll = document.getElementById('chatbox');
scroll.scrollTop = scroll.scrollHeight;
}
});
}
</script>
<?php
}
?>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
</script>
</body>
</html>
The chat.php
<!DOCTYPE HTML>
<head>
<title>Chat</title>
<META HTTP-EQUIV="content-type" CONTENT= "text/html; charset=UTF-8">
</head>
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'db_57218');
define('DB_USER','u57218');
define('DB_PASSWORD','27222528');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Failed to connect to MySQL: " . mysqli_error());
$query = "SELECT * FROM Messages";
if($result = mysqli_query ($con, $query)){
while ($row = mysqli_fetch_row($result))
{if($row['4']==0){
echo '('.$row['5'].') <b>'.$row['1'].'</b>: '.$row['2'].'<br>';
}
else{echo 'Ο χρήστης <b>'.$row['1'].'</b> '.$row['2'].'<br>';}
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
You can store the last message id which you played sound for, and at every refresh action, you can check if the last message id is equals to id you stored before. If not, you play sound.
To be more clear:
$lastMessageId=5;
$lastMessageIdWePlayedSoundFor=4;
if($lastMessageId!=$lastMessageIdWePlayedSoundFor)
{
////play sound here
$lastMessageIdWePlayedSoundFor=$lastMessageId;
}
So whenever there is a new message we haven't played a sound for it's existance, we play sound. You can use this algorithm.
Jquery keyup function is very slow. i am outputting the text on image. but the output is very slow.
Following is the html, JS, PHP code that i run. The code is running fine on my side but the problem is that it is very slow almost 5 to 10 seconds to write a letter. Is there any way to speed up the process. Kindly help.
jQuery(document).ready(function(){
//PURE PATH TO IMAGE GENERATING PHP FILE
var base = jQuery(".preview img").attr("src");
//GATHER IMAGE FOR FIRST TIME
jQuery(".preview img").attr("src",base+'?'+jQuery("#realtime-form").serialize());
//KEYUP EVENT AND NEW IMAGE GATHER
jQuery("#realtime-form input,textarea").stop().keyup(function(){
jQuery(".preview img").attr("src",base+'?'+jQuery("#realtime-form").serialize());
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" src="http://nameonbirthdaycake.com/scripts/client-side.js"></script>
<div id="mainwrapper" class="preview">
<div id="box-1" class="box">
<img class="downloadable" src="http://nameonbirthdaycake.com/scripts/write.php?user_input=Enter+the+Name&postid=7">
</div>
<form id="realtime-form" action="" method="post"><strong>Enter the Name</strong>
<input id="realtime-form" maxlength="12" name="user_input" type="text" value="Enter the Name"/>
</form></div>
<?php
header ('Content-type: image/png');
if(isset($_GET["postid"])){
$post=(int)$_GET["postid"];
if ($post==7){
$userinput = $_GET["user_input"];
$image=imagecreatefrompng(__DIR__ . "/images/bg.png");
$font = __DIR__ . '/fonts/PR8Charade.ttf';
$col1 = imagecolorallocate($image, 129, 125,11);
$text_size1 = 36;
$xposition1 = 245;
$yposition1 = 380;
$angeldirection1 = 50;
imagettftext($image, $text_size1, $angeldirection1, $xposition1, $yposition1, $col1, $font, $userinput);
imagepng($image);
imagedestroy($image);
}
}
?>
here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.
I'm doing a small project where I'm trying to create a continual gallery for a user; whereby, they upload a file, and it immediately appears on the same page. The one thing I can't manage to accomplish is to keep the files there on the page even if the page is refreshed. In other words, I want the user to return and see all of their uploaded files as if they never left, until they close the browser. I've tried using cookies and session variables but I'm confused on how to implement this. Here is my Code. I APOLOGIZE IN ADVANCE FOR BAD INDENTATION.
My index.php:
<?php
// Process image
$uploadName = 'uploaded/pic.jpg';
if (count($_FILES))
move_uploaded_file($_FILES['image']['tmp_name'], $uploadName);
?>
<!DOCTYPE html>
<html>
<head>
<style>
li { display: inline-block; padding: 200px; width: 200px;}
img { width: 100%; height:100%;}
</style>
<script type="text/javascript">
function iframeSubmit(formElem, action, callback) {
// name a callback that will be called from inside the iframe
var callbackName = 'iframe' + Math.ceil(Math.random() * 10000);
action = action + (action.indexOf('?') == -1 ? '?' : '&') + 'callback='+
callbackName;
// create an iframe and use the callback as its name
var iframe = document.createElement('iframe');
iframe.setAttribute('name', callbackName);
iframe.style.display = 'none';
// add the target and edit the action of the form
formElem.setAttribute('target', callbackName);
formElem.setAttribute('action', action);
// add the hidden iframe after the form
formElem.parentNode.appendChild(iframe);
window[callbackName] = callback;
}
;
</script>
</head>
<body onload="onload()">
Home
Schedule
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
<ul>
<?php if (count($_FILES)): ?>
<li><img src="<?php echo $uploadName ?>"/></li>
<?php endif; ?>
</ul>
<script type="text/javascript">
function onload() {
}
</script>
<script type="text/javascript">
function processResponse(response) {
if (!response.success) {
alert('woopsie');
return;
}
var newListItem = document.createElement('li');
newListItem.innerHTML = '<img src="' + response.path + '"/>';
document.getElementsByTagName('ul')[0].appendChild(newListItem);
}
function onload() {
iframeSubmit(document.getElementsByTagName('form')[0], 'upload.php',
processResponse);
}
</script>
</body>
</html>
Here is my upload.php:
<?php
enter code here
$imagePath = 'uploaded/pic.jpg';
setcookie("cookie", "stuff", time() + 3600, $uploadName);
move_uploaded_file($_FILES['image']['tmp_name'], $imagePath);
?>
<!DOCTYPE html>
<html>
<head>Iframe content</head>
<body>
<script type="text/javascript">
<?php
echo 'window.parent[\'' . $_GET['callback'] . '\']('
. json_encode(array('success' => true, 'path' => $imagePath)) . ')';
?>
</script>
</body>
</html>