How to load image which of last upload? - php

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>

Related

Show file link after uploading

I've downloaded an image uploading script with Ajax from this Link
The codes are:
index.php
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + str+'<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
Uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result.",".$target_path; ?>);</script>
I want to show the url of uploaded image. So that it can be use instantly.
I've a little knowledge about ajex. I tried by writing two three of codes but it's not working.
Anyone can help to show the file url.
Thanks in advance.
Hope this helps...
index.php
<html>
<head>
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str, filename){
var result = '';
var file_link = '';
var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
file_link = "<br/><a href='"+directoryPath+"/"+filename +"'>"+filename+"</a><br/>";
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + file_link +'<br/><br/><label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="ajax-uploader.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
</body>
</html>
ajax-uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
$actual_name = basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.stopUpload(<?php echo "$result, '$target_path','$actual_name' "; ?>);</script>
change Uploader.php to upload.php.
Add php code after sleep as follows..
sleep(1);
$target_path = str_replace('\\', '/', $target_path);
$spath = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/".$_FILES['myfile']['name'];
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo "'".$result."','".$target_path.',img url :'.$spath."'";?>);</script>

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 update image in mysql blob with Jcrop Update Coords php

PROBLEM IS CLEAR THANKS FOR FEED BACK
I want to upload image at mysql after square crop using php and jcrop.
I have this type of code but it is not wroking plz help me...
HTML
<form name="upload.php" enctype="multipart/form-data" action="" method="post"class="frmImageUpload">
<label>Profile Picture:</label><br/>
<img id="blah" class="crop" src="pro.png" style="width:500px;maxwidth:500px;height:width;max-height:500px;" border="1" />
<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" />
<div class="file_button_container">
<input name="userImage" type="file" id="userImage" /></div>
<input type="submit" value="Upload" class="btnSubmit" />
</from>
Script
<script type='text/javascript' src="http://jcropcdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://jcropcdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.min.css">
<style type='text/css'>
#blah {
background-color: #000;
width: 500px;
font-size: 24px;
display: block;
}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
$('.crop').Jcrop({
onSelect: updateCoords,
bgOpacity: .4,
setSelect: [ 500, 10, 10, 10 ],
aspectRatio: 16 / 16
});
}
reader.readAsDataURL(input.files[0]);
}
}
$("#userImage").change(function(){
console.log(this);
readURL(this);
});
function updateCoords(c)
{
console.log(c);
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
});//]]>
</script>
Upload.PHP (I think, It is not work )
<?php
$max_file_size = 1000 * 1024;
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
$conn = mysql_connect("LOCAL", "USERNAME", "PASSWORD");
mysql_select_db("DB NAME");
$nw = $nh = 200;
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
$h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
$data = addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$vImg = imagecreatefromstring($data);
$dstImg = imagecreatetruecolor($nw, $nh);
$imgData = imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$imgt = $imageProperties['mime'];
$stet = $_POST['stet'];
$sql ="UPDATE users SET
imageType='$imgt',
imageData='$imgData',
stet='$stet'
WHERE id=" . $_SESSION['user']['id'];
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: index.php");
}
}
else
{
echo 'file is too small or large';
}
}}
?>
What is problem in this code plz defind me quickly
I want to store image in MySQL BLOB after jcrop using php..

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