jcrop is saving image which is just black background - php

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:
?>

Related

PHP mt_rand not working

I'm trying to post a random value from a form's hidden input type.. but it's not posting any values..
using a function to post the values..
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
$('#multiple_upload_form').ajaxForm({
target:'#images_preview',
beforeSubmit:function(e){
$('.uploading').show();
},
success:function(e){
$('.uploading').hide();
},
error:function(e){
}
}).submit();
});
});
</script>
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="randnum" id ="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
and this is upload.php
if($_POST['image_form_submit'] == 1)
{
$rand = $_POST['randnum'];
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
?>
I'm trying to store a random number every time the form gets posted...
You need to echo the value produced by mt_rand() like below:-
<input type="hidden" name="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
Note:- your code along with my change is working fine if i changed (form.js library file):-
<script type="text/javascript" src="jquery.form.js"></script><!--local URL-->
To:-
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script><!-- I used live URL -->
Instead of
<input type="hidden" name="randnum" id ="randnum"
value="<?php echo mt_rand(1000,10000000); ?>" />
You can generate after submitting form in php code
$rand=mt_rand(1000,10000000);
this will help you to generate key everytime you submit file to upload
if($_POST['image_form_submit'] == 1)
{
$rand = mt_rand(1000,10000000);
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
Please use try this,
Your ajax script is not working try this and check if opening and closing {} having error
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Bootstrap Starter</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
/*CUSTOM CODE HERE*/
</style>
</head>
<body>
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="randnum" id ="randnum" value="<?php echo mt_rand(1000,10000000); ?>" />
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
<script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type='text/javascript' src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#images').on('change',function(){
var formObj = $("#multiple_upload_form");
var formURL = formObj.attr("action");
var formData = new FormData(formObj[0]);
$('.uploading').show();
$.ajax({
url: formURL,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{
console.log(data);
$('.uploading').hide();
}
});
});
});
</script>
</body>
</html>
<?php
if($_POST['image_form_submit'] == 1)
{
$rand = $_POST['randnum'];
$con=new PDO("mysql:host=localhost;dbname=newimg","root","");
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
$target_dir = "uploads/";
$target_file = $target_dir.$_FILES['images']['name'][$key];
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$target_file)){
$images_arr[] = $target_file;
$addnew=$con->prepare("INSERT INTO attempt010(link,name,size,type)VALUES('$rand','$image_name','$size','$type')");
$addnew->execute();
}
}
$fetch_imgid=$con->prepare("SELECT * FROM attempt010 where link='$rand'");
$fetch_imgid->setFetchMode(PDO:: FETCH_ASSOC);
$fetch_imgid->execute();
}
?>

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

How to load image which of last upload?

I am loading a image which is jpg but what if the user uploads a png file or jpeg file as profile image where he already had a file in jpg.
SAME NAME example : abc#mail.com_profileimage.ext
I am getting this image by direct link through url.
<img style="width: 100%" src="http://proconstruct.co.in/upload_images/<?php echo $email.'_profileimage.jpg';?>" onerror="this.src = 'http://proconstruct.co.in/images/noimage.jpg'; ">
If i use $images = glob($dirname . "*"); with the give prefix above how can i get last saved image
UPLOAD and CROP CODE
<?php
error_reporting (E_ALL ^ E_NOTICE);
$upload_path = "upload_images/";
$thumb_width = "150";
$thumb_height = "150";
function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
list($imagewidth, $imageheight, $imageType) = getimagesize($image);
$imageType = image_type_to_mime_type($imageType);
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
switch($imageType) {
case "image/gif":
$source=imagecreatefromgif($image);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
$source=imagecreatefromjpeg($image);
break;
case "image/png":
case "image/x-png":
$source=imagecreatefrompng($image);
break;
}
imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
switch($imageType) {
case "image/gif":
imagegif($newImage,$thumb_image_name);
break;
case "image/pjpeg":
case "image/jpeg":
case "image/jpg":
imagejpeg($newImage,$thumb_image_name,100);
break;
case "image/png":
case "image/x-png":
imagepng($newImage,$thumb_image_name);
break;
}
chmod($thumb_image_name, 0777);
return $thumb_image_name;
}
if (isset($_POST["upload_thumbnail"])) {
$filenam = $_POST['filename'];
$filenam = pathinfo($filenam);
$extn = $filenam['extension'];
$large_image_location = $upload_path.$_POST['filename'];
$thumb_image_location = $upload_path."thumb_".$_POST['filename'];
$myemail = $this->session->userdata('email');
$thumb_image_location = $upload_path.$myemail."_profileimage.".$extn;
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload File and Crop</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/cropimage.css" />
<link type="text/css" href="css/imgareaselect-default.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/jquery.imgareaselect.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$('#submitbtn').click(function() {
$("#viewimage").html('');
$("#viewimage").html('<img src="images/loading.gif" />');
$(".uploadform").ajaxForm({
url: 'upload_sup',
success: showResponse
}).submit();
});
});
function showResponse(responseText, statusText, xhr, $form){
if(responseText.indexOf('.')>0){
$('#thumbviewimage').html('<img src="<?php echo $upload_path; ?>'+responseText+'" style="position: relative;" alt="Thumbnail Preview" />');
$('#viewimage').html('<img class="preview" alt="" src="<?php echo $upload_path; ?>'+responseText+'" id="thumbnail" />');
$('#filename').val(responseText);
$('#thumbnail').imgAreaSelect({ aspectRatio: '1:1', handles: true , onSelectChange: preview });
}else{
$('#thumbviewimage').html(responseText);
$('#viewimage').html(responseText);
}
}
</script>
<script type="text/javascript">
function preview(img, selection) {
var scaleX = <?php echo $thumb_width;?> / selection.width;
var scaleY = <?php echo $thumb_height;?> / selection.height;
$('#thumbviewimage > img').css({
width: Math.round(scaleX * img.width) + 'px',
height: Math.round(scaleY * img.height) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
var x1 = Math.round((img.naturalWidth/img.width)*selection.x1);
var y1 = Math.round((img.naturalHeight/img.height)*selection.y1);
var x2 = Math.round(x1+selection.width);
var y2 = Math.round(y1+selection.height);
$('#x1').val(x1);
$('#y1').val(y1);
$('#x2').val(x2);
$('#y2').val(y2);
$('#w').val(Math.round((img.naturalWidth/img.width)*selection.width));
$('#h').val(Math.round((img.naturalHeight/img.height)*selection.height));
}
$(document).ready(function () {
$('#save_thumb').click(function() {
var x1 = $('#x1').val();
var y1 = $('#y1').val();
var x2 = $('#x2').val();
var y2 = $('#y2').val();
var w = $('#w').val();
var h = $('#h').val();
if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
alert("Please Make a Selection First");
return false;
}else{
return true;
}
});
});
</script>
</head>
<body style="background-color: #6db4e7">
<!-- content -->
<section>
<div class="container">
<div class="crop_box">
<form class="uploadform" method="post" enctype="multipart/form-data" action='upload.php' name="photo">
<div class="crop_set_upload">
<div class="crop_upload_label">Upload files: </div>
<div class="crop_select_image"><div class="file_browser"><input type="file" name="imagefile" id="imagefile" class="hide_broswe" /></div></div>
<div class="crop_select_image"><input type="submit" value="Upload" class="upload_button" name="submitbtn" id="submitbtn" /></div>
</div>
</form>
<div class="crop_set_preview">
<div class="crop_preview_left">
<div class="crop_preview_box_big" id='viewimage'>
</div>
</div>
<div class="crop_preview_right">
Preview Image
<div class="crop_preview_box_small" id='thumbviewimage' style="position:relative; overflow:hidden;"> </div>
<form name="thumbnail" action="profileimage" method="post">
<input type="hidden" name="x1" value="" id="x1" />
<input type="hidden" name="y1" value="" id="y1" />
<input type="hidden" name="x2" value="" id="x2" />
<input type="hidden" name="y2" value="" id="y2" />
<input type="hidden" name="w" value="" id="w" />
<input type="hidden" name="h" value="" id="h" />
<input type="hidden" name="wr" value="" id="wr" />
<input type="hidden" name="filename" value="" id="filename" />
<div class="crop_preview_submit"><input type="submit" name="upload_thumbnail" value="Save Thumbnail" id="save_thumb" class="submit_button" /> </div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>

How to show cropped image on same page

I want to be able to crop a file three time (so you have a big, medium and small image). The problem right now is that the JCrop is working. Uploading the file works, and you can actually "crop" the file. The problem is that the cropped file is not shown when pressed on the submit button.
As you can see in the code I use a function ShowCrop to keep things tidy, the function is called before the submit form begins. When I run the page I see nothing (no form, no image). Something obviously goes wrong that this function.
I am a beginning PHP scripter, and I am sure there are a lot of faults in this script. Please remind me of those so I can learn!
Here's the code:
<?php
//Original upload
if(isset($_POST['upload'])) {
$name = '_original';
$path_info = pathinfo($_FILES['afbeelding']['name']);
$file_extension = $path_info["extension"];
$newname = $path_info['filename'].$name.".".$file_extension;
move_uploaded_file($_FILES['afbeelding']['tmp_name'], 'images/' . $newname);}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php echo $newname ?>
Big format:
<form method="post" action="upload.php">
<input type="hidden" name="x" value="" />
<input type="hidden" name="y" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="hidden" name="fextension" value="<?php echo $file_extension ?>" />
<input type="hidden" name="name" value=<?php echo $newname ?> />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form>
<?php
echo '<img src="getimage.php?file=images/' . $newname . '">';
}
phpinfo();
}
else if(isset($_POST['x'])) //GROOT -> MIDDEL
{
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<?php
echo $_POST['name'];
showCrop($_POST['fextension']);
//echo '<img src="getimage.php?file=images/' . $_POST['name'] . '">';
?> Middel formaat:
<form method="post" action="upload.php">
<input type="hidden" name="x" value="" />
<input type="hidden" name="y" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="hidden" name="image" value="images/<?php echo $_FILES['afbeelding'][$newname]; ?>" />
<input type="submit" value="Crop image!" />
</form><?php
}
function showCrop($ext){
$targ_w = $_POST['w'];
$targ_h = $_POST['h'];
$jpeg_quality = 90;
$src = $_POST['image'];
switch($ext)
{
case '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']);
//header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
break;
case 'png';
$img_r = imagecreatefrompng($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']);
move_uploaded_file($dst_r, 'images/' ."test". $newname);
break;
exit;
}
}
?>
I've rewritten the logic of the code so it'll automatically reload the page until each size/crop has been completed.
This isn't pretty code and is lacking a lot of additional functions (database, security, etc), but it demonstrates how you can achieve what you need (hopefully).
<?php
// Resize image and return filename
function saveCrop($source, $destination) {
// Get extension
$ext = strtolower(pathinfo($source, PATHINFO_EXTENSION));
// Resize/Crop image
switch($ext)
{
case 'jpg';
$img_r = imagecreatefromjpeg($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagejpeg($dst_r, $destination);
return true;
break;
case 'png';
$img_r = imagecreatefrompng($source);
$dst_r = ImageCreateTrueColor($_POST['w'], $_POST['h']);
imagecopyresampled($dst_r,$img_r, 0, 0, $_POST['x'], $_POST['y'], $_POST['w'], $_POST['h'], $_POST['w'], $_POST['h']);
imagepng($dst_r, $destination);
return true;
break;
default:
die('Invalid file extension: ' . $ext);
}
}
// Save uploaded file to web server for future processing
if ( isset($_FILES['uploaded-file']))
{
// Check for valid file type
$ext = strtolower(pathinfo($_FILES['uploaded-file']['name'], PATHINFO_EXTENSION));
if ( ! in_array($ext, array('jpg', 'png')))
{
die('Unsupported file type');
}
$source_file = 'images/original-' . $_FILES['uploaded-file']['name'];
if ( ! move_uploaded_file($_FILES['uploaded-file']['tmp_name'], $source_file))
{
die('Unable to move uploaded file (possibly due to write permissions)');
}
// Set target file
$target_file = 'images/large-' . $_FILES['uploaded-file']['name'];
}
// Process crop/resize requests
elseif (isset($_POST['x']))
{
$source_file = $_POST['source'];
$target_file = $_POST['target'];
saveCrop($source_file, $target_file);
// No more cropping is required after the small image
if (substr($target_file, 0, 12) == 'images/small')
{
header('Location: completed.php');
}
else
{
// Determine new source file
$source_file = $target_file;
// Determine new target file
$target_file = str_replace(
array('images/medium', 'images/large', 'images/original'),
array('images/small', 'images/medium', 'images/large'),
$target_file
);
}
}
?>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript" src="http://www.noobtutorials.nl/voorbeelden/jquery.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript">
$( function () {
$('img').Jcrop({
setSelect: [150, 150, 500, 500],
onSelect: function (c) {
$("input[name=x]").val(c.x);
$("input[name=y]").val(c.y);
$("input[name=w]").val(c.w);
$("input[name=h]").val(c.h);
}
});
});
</script>
<form method="post" action="">
<input type="text" name="x" value="" />
<input type="text" name="y" value="" />
<input type="text" name="w" value="" />
<input type="text" name="h" value="" />
<input type="text" name="source" value="<?php echo $source_file; ?>" />
<input type="text" name="target" value="<?php echo $target_file; ?>" />
<input type="submit" value="Crop" />
</form>
<img src="<?php echo $source_file; ?>" id="img">

Preview image not shwing up after cropping with jcrop

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.

Categories