Preview image not shwing up after cropping with jcrop - php

I have created a new way of uploading my images using two different php pages.
1 does the uploading while thye other does the cropping. Inpart it seems to work to an extent I had to set permissions on the folder it was saving to and it seemed to work but know it does not for some strange reason. It suppose to save a copy of the cropped image to the same folder but it does not seem to do that at the moment. I have no idea why it worked and has stopped working. I have been looking at the code for a while but for the life of me can't see the problem I am reletively new to php but it seems to be a solution to being able to upload images and crop them wether you are using IE 8,9 or the other browsers.
Here is the code for the upload.php section:
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
</head>
<body >
<?php
$folder = 'imgtest/';
$orig_w = 500;
if(isset($_POST['submit']) )
{
$imageFile = $_FILES['image']['tmp_name'];
$filename = basename( $_FILES['image']['name']);
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$orig_h = ($height/$width) * $orig_w;
$tmp = imagecreatetruecolor($orig_w,$orig_h);
imagecopyresampled($tmp, $src, 0,0,0,0, $orig_w,$orig_h,$width,$height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
$filename = urlencode($filename);
header("Location: crop.php?filename=$filename&height=$orig_h");
}
?>
<h1>php Upload Form</h1>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<label for="image">Image:</label>
<input type="file" name="image" id="image"/><br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Image!"/>
</p>
</form>
</body>
<script>
</script>
</html>
and here is the code for the crop section :
<?php
$folder = 'imgtest/';
$filename = $_GET['filename'];
$orig_w = 500;
$orig_h = $_GET['height'];
$targ_w = 120;
$targ_h = 100;
$ratio = $targ_w / $targ_h;
if (isset($_POST['submit']))
{
$src = imagecreatefromjpeg($folder.$filename);
$tmp = imagecreatetruecolor($targ_w, $targ_h);
imagecopyresampled($tmp, $src, 0,0,$_POST['x'],$_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);
imagejpeg($tmp, $folder.'t_'.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
echo "<h1> Saved Thumbnail</h1> <img src=\"$folder/t_$filename\"/>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php crop form</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
<script type="text/javascript" src="js/jquery-1.9.1.min.js" ></script>
<script type="text/javascript" src="js/jquery.Jcrop.js" ></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css"/>
<style type="text/css">
#preview
{
width: <?php echo $targ_w?>px;
height:<?php echo $targ_h?>px;
overflow:hidden;
}
</style>
</head>
<body >
<h1>Jcrop Plugin Behavior</h1>
<table>
<tr>
<td>
<img src="<?php echo $folder.$filename?>" id="cropbox" alt="cropbox" />
</td>
<td>
Thumb Preview:
<div id="preview">
<img src="<?php echo $folder.$filename?>" alt="thumb" />
</div>
</td>
</tr>
</table>
<form action="<?php echo $_SERVER['REQUEST_URI']?>" method="post">
<p>
<input type="hidden" id="x" name="x"/>
<input type="hidden" id="y" name="y"/>
<input type="hidden" id="w" name="w"/>
<input type="hidden" id="h" name="h"/>
<input type="submit" id="submit" value="Crop Image!"/>
</p>
</form>
</body>
<script type="text/javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: <?php echo $ratio?>,
setSelect:[0,0,<?php echo $orig_w.','.$orig_h;?>],
onSelect:updateCoords,
onChange:updateCoords
});
});
function updateCoords(c)
{
showPreview(c);
$("#x").val(c.x);
$("#y").val(c.y);
$("#w").val(c.w);
$("#h").val(c.h);
}
function showPreview(coords)
{
var rx =<?php echo $targ_w;?> / coords.w
var ry =<?php echo $targ_h;?> / coords.h
$("#preview img").css({
width: Math.round(rx*<?php echo $orig_w;?>)+'px',
height: Math.round(ry*<?php echo $orig_h;?>)+'px',
marginLeft: '-' + Math.round (rx*coords.x)+'px',
marginTop: '-' + Math.round(ry*coords.y)+'px'
});
}
</script>
</html>
Help would be greatly appreciated.

Headers(in this case location php headers) have to be sent before any content already echoed. So move your php part in your upload.php to top of that file:
<?php
$folder = 'imgtest/';
$orig_w = 500;
if(isset($_POST['submit']) )
{
$imageFile = $_FILES['image']['tmp_name'];
$filename = basename( $_FILES['image']['name']);
list($width, $height) = getimagesize($imageFile);
$src = imagecreatefromjpeg($imageFile);
$orig_h = ($height/$width) * $orig_w;
$tmp = imagecreatetruecolor($orig_w,$orig_h);
imagecopyresampled($tmp, $src, 0,0,0,0, $orig_w,$orig_h,$width,$height);
imagejpeg($tmp, $folder.$filename, 100);
imagedestroy($tmp);
imagedestroy($src);
$filename = urlencode($filename);
header("Location: crop.php?filename=$filename&height=$orig_h");
}
?>
<!DOCTYPE html PUBLIC "-//W3C// XHHTML 1.0 Strict//EN" "http://www.w3.org/TR/XHTML/DTD/xhtml1-strict.dtd" >
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"/>
</head>
<body >
<h1>php Upload Form</h1>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
<p>
<label for="image">Image:</label>
<input type="file" name="image" id="image"/><br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Image!"/>
</p>
</form>
</body>
<script>
</script>
</html>
Tell if its still not working.

Related

apache2 not loading a php script with form upload, but can load php file without form upload

i put this code at /var/www/html as index.php and i chmod 777 to this file
<?php
if(isset($_POST['btn-upload']))
{
$img = rand(1000,100000)."-".$_FILES['img']['name'];
$img_loc = $_FILES['img']['tmp_name'];
$folder="uploads/";
if(move_uploaded_file($img_loc,$folder.$img))
{
echo "<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert('Upload%20Sukses!!!')%3B%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />";
}
else
{
echo "<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%3Ealert('Upload%20Gagal')%3B%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload file dengan PHP</title>
</head>
<body>
<br />
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<button type="submit" name="btn-upload">upload</button>
</form>
<p>
</body>
</html>
it shows blank screen, but if i run this php code
<?php
echo "test"
?>
it run perfectly

my cropped image is just a black colored box of 2KB?

Im using the following PHP code to save a cropped image from jcrop.
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = "../profiles/";
$src = $target . basename( $_FILES['userfile']['name']);
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r, "simple2.jpg", $jpeg_quality);
A simple2.jpg does get saved in the directory, but it is just a black colored square of size 2 KB. I want the cropped part to be saved. How to fix this?
Use this
index.php
<html lang="en" >
<head>
<meta charset="utf-8" />
<meta name="author" content="Script Tutorials" />
<title>HTML5 Image uploader with Jcrop | Script Tutorials</title>
<!-- add styles -->
<link href="css/main.css" rel="stylesheet" type="text/css" />
<link href="css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
<!-- add scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<header>
<h2>HTML5 Image uploader with Jcrop </h2>
</header>
<div class="demo">
<div class="bheader"><h2>-- Image upload form --</h2></div>
<div class="bbody">
<!-- upload form -->
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm()">
<!-- hidden crop params -->
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<h2>Step1: Please select image file</h2>
<div>
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" />
</div>
<div class="error"></div>
<div class="step2">
<h2>Step2: Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label>
<input type="text" id="filesize" name="filesize" />
<label>Type</label>
<input type="text" id="filetype" name="filetype" />
<label>Image dimension</label>
<input type="text" id="filedim" name="filedim" />
<label>W</label> <input type="text" id="w" name="w" />
<label>H</label> <input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
</div>
</div>
</body>
</html>
upload.php
<?php
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// $iWidth = $iHeight = 200; // desired image result dimensions
$iWidth=abs($_POST['x2']-$_POST['x1']);
$iHeight=abs($_POST['y2']-$_POST['y1']);
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'cache/' . md5(time().rand());
// mkdir("cache",0664,true);
chmod('cache', 0664);
//echo $url = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
//echo '<br>';
$root=$_SERVER['DOCUMENT_ROOT'];
$newsTempFileName = $root.'/beta/nikhil/demo/jquery-images-direct-crop/'.$sTempFileName;
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $newsTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
?>
Live Demo : https://www.script-tutorials.com/demos/316/index.html
add jquery and css

I am not getting the output for this script

i have written a code but that is not working. below is a code which enters an image into the database on user input. But my problem is that when i am calling it to print on page, nothing is diaplaying, please help me here.
<?php
$conx=mysqli_connect('localhost','root','sultan','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
$theme=$_POST['theme'];
$sql = "UPDATE colors SET theme='$theme' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo $theme ?>) ;}
</style>
</head>
<body>
<form method="post">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>
You need to terminate the statement.
current
<?php echo $theme ?>
new
<?php echo $theme; ?>
<?php
$conx=mysqli_connect('localhost','root','','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
// new code
$path = '/';
$fileName = $_FILES['theme']["name"];
$fileTmpLoc = $_FILES['theme']["tmp_name"];
$temp = explode(".", $_FILES['theme']["name"]);
$extension = end($temp);
$temp = explode('.', $fileName );
$ext = array_pop($temp );
$name = implode('.', $temp );
$FileNM = $name.time().".".$extension;
$theme = $FileNM.$ext;
move_uploaded_file($_FILES['theme']["tmp_name"], $theme);
$sql = "UPDATE colors SET theme='$theme' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo $theme; ?>) ;}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>
<?php
$conx=mysqli_connect('localhost','root','','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
// new code
$error1="";
$error2="";
if ($_FILES["theme"]["type"] !== "image/jpeg"){
echo $error1 = "File is not in JPG!";
}else{
$error1="";
}
if(($_FILES["theme"]["size"] > 1024)){
echo $error2 = "File size not allowed more than 1 MB!";
}else{
$error2="";
}
if($error1 =="" && $error2==""){
$fileName = $_FILES['theme']["name"];
$fileTmpLoc = $_FILES['theme']["tmp_name"];
$temp = explode(".", $_FILES['theme']["name"]);
$extension = end($temp);
$temp = explode('.', $fileName );
$ext = array_pop($temp );
$name = implode('.', $temp );
$FileNM = $name.time().".".$extension;
move_uploaded_file($_FILES['theme']["tmp_name"], "img/".$FileNM);
$sql = "UPDATE colors SET theme='$FileNM' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo "img/".$FileNM; ?>) ;}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>

Uploaded images not in image folder

I just made a file upload code and I was wondering why the file upload wasn't working? I checked the permission of my image folder in localhost and that seems to be ok. I don't know where the problem exactly is. Any ideas?
<?php
require "config.php";
require "functions.php";
require "database.php";
if(isset($_FILES['fupload'])){
$filename = addslashes($_FILES['fupload']['name']);
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
$description = addslashes($_POST['description']);
$src = $path_to_image_directory . $filename;
$tn_src = $path_to_thumbs_directory . $filename;
if (strlen($_POST['description'])<4)
$error['description'] = '<p class="alert">Please enter a description for your photo</p>';
if($filename == '' || !preg_match('/[.](jpg)|(gif)|(png)|(jpeg)$/', $filename))
$error['no_file'] = '<p class="alert">Please select an image, dummy! </p>';
if (!isset($error)){
move_uploaded_file($source, $target);
$q = "INSERT into photo(description, src, tn_src)VALUES('$description', '$src','$tn_src')";
$result = $mysqli->query($q) or die (mysqli_error($myqli));
if ($result) {
echo "Succes! Your file has been uploaded";
}
createThumbnail($filename);
}
}
?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Upload</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>My photos</h1>
<ul><?php getPhotos(); ?></ul>
<h2>Upload a photo</h2>
<form enctype="multipart/form-data" action="index.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="fupload" /><br/>
<textarea name="description" id="description" cols="50" rows="6"></textarea><br/>
<input type="submit" value="Upload photo" name="submit" />
</form>
<?php
if (isset($error["description"])) {
echo $error["description"];
}
if (isset($error["no_file"])) {
echo $error["no_file"];
}
?>
</body>
</html>
Please make sure that you appended directory separator in $path_to_thumbs_directory.
And you don't need to use addslashes to $filename.

jcrop is saving image which is just black background

I am using jcrop to crop and save image but what i get is black image , what is the problem in below code:
Second :: also it navigate to some other page , i dont want navigation . how to do that ?
<?php
/**
* Jcrop image cropping plugin for jQuery
* Example cropping script
* #copyright 2008-2009 Kelly Hallman
* More info: http://deepliquid.com/content/Jcrop_Implementation_Theory.html
*/
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r,'null.jpg',$jpeg_quality);
exit;
}
// If not a POST request, display page below:
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<script language="Javascript">
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Please select a crop region then press submit.');
return false;
};
</script>
</head>
<body>
<!-- This is the image we're attaching Jcrop to -->
<img src="demo_files/pool.jpg" id="cropbox" />
<!-- This is the form that our event handler fills -->
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value="Crop Image" />
</form>
</body>
</html>
I solved by changing it to following code,
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
imagejpeg($dst_r,'hello.jpg',$jpeg_quality);
exit;
}
// If not a POST request, display page below:
?>

Categories