I am working on image cropping in PHP Codeigniter, below is my code that I have tried. When I gave the path of the image, the code worked fine, means I can select the area of the image to crop. But when I tried the same code with user uploaded image( user upload image and then crop), I cannot select image area of uploaded image. How to select image area of an image uploaded by user? I am using JCrop plugin.
imagecrop
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Jcrop Dynamic Avatar JS/PHP Demo</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/jquery.Jcrop.css">
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript" src="js/cropsetup.js"></script>
</head>
<body>
<div id="wrapper">
<div class="jc">
<input type='file' name="userfile" size="20"
onchange="readURL(this);"/>
<img src="#" id="target" alt="[Jcrop Example]" />
<div id="preview-pane">
<div class="preview-container">
<img src="#" class="jcrop-preview" alt="Preview" />
</div>
</div>
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php"
target="_blank">
<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!">
</form>
</div>
</div>
</div>
<script>function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}</script>
</body>
</html>
PHP code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = 'images/cropimg.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);
exit;
}
?>
This is Javascript code:
$(function($){
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
bgOpacity: 0.5,
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
}
});
The jQuery pluging ImageSelectArea worked for me !
http://odyniec.net/projects/imgareaselect/
Code is provided below:
<html>
<link rel="stylesheet" href="css/imgareaselect.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/jquery.imgareaselect.js"></script>
<body>
<form action="crop.php" method="post" enctype="multipart/form-data">
Upload Image: <input type="file" name="image" id="image" />
<input type="hidden" name="x1" value="" />
<input type="hidden" name="y1" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" /><br><br>
<input type="submit" name="submit" value="Submit" />
</form>
<p><img id="previewimage" style="display:none;"/></p>
</body>
<script>
jQuery(function($) {
var p = $("#previewimage");
$("body").on("change", "#image", function(){
var imageReader = new FileReader();
imageReader.readAsDataURL(document.getElementById("image").files[0]);
imageReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
$('#previewimage').imgAreaSelect({
onSelectEnd: function (img, selection) {
$('input[name="x1"]').val(selection.x1);
$('input[name="y1"]').val(selection.y1);
$('input[name="w"]').val(selection.width);
$('input[name="h"]').val(selection.height);
}
});
});
</script>
</html>
Related
I have a scenario in which user is prompted for selecting a file from local disk (an image). Upon selection, this image is shown in browser (without uploading). After seeing the image user inputs a number in CN No field. Upon submit I want to rename the file on local disk with the number input by user. Is there some way to do this in code using PHP or Javascript?
<html>
<head>
<script type='text/javascript'>
function preview_image(event)
{
var reader = new FileReader();
reader.onload = function()
{
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
</head>
<body>
<form>
Select File: <input type="file" accept="image/*" onchange="preview_image(event)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u"> <br>
</form>
<img id="output_image" style="width: 400px"/>
</body>
</html>
You could do this, presuming downloading the file is ok.
<html>
<head>
<script type='text/javascript'>
var img;
function preview_image(elm) {
var reader = new FileReader();
reader.onload = function(event) {
img = event.target.result
document.getElementById("image_preview").src = img;
};
reader.readAsDataURL(elm.files[0]);
}
function download() {
var element = document.createElement('a');
element.setAttribute('href', img)
element.setAttribute('download', document.getElementById("cnno").value+'.png');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
</head>
<body>
Select File: <input type="file" accept="image/*" onchange="preview_image(this)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u" onclick="download()"><br>
<img id="image_preview" style="width: 400px"/>
</body>
</html>
try this:
var file = document.GetElementById('fileupload1');
var blob = file.files[0].slice(0, -1, 'image/png');
newFile = new File([blob], 'name.png', {type: 'image/png'});
But its only for image rename.
I am just trying to submit a form using jquery ajax and for that i m using the FormData but whenever i click on the submit button the page reloads without showing any kind of error or any kind of result.
This is the Form Part name is regpage.php
<!DOCTYPE html>
<html>
<head>
<title>reg form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
#d1
{
width: 400px;
height: auto;
border: 1px solid;
text-align: center;
margin: 0 auto;
}
</style>
</head>
</head>
<body>
<form id="form" method="post" enctype="multipart/form-data">
<div id="d1">
<h1>Regestration form</h1>
username:<input type="text" name="uname" id="username" placeholder="username"><br>
password:<input type="password" name="pass" id="password" placeholder="password"><br>
email:<input type="text" name="email" id="email" placeholder="email"><br>
<span>Hobby</span>
<input type="checkbox" name="cric[]" value="cricket">Cricket
<input type="checkbox" name="cric[]" value="kite">Kite
<input type="checkbox" name="cric[]" value="zym">ZYM<br>
<h2>Gender</h2>
<input type="radio" name="chack" id="d3" value="male">male
<input type="radio" name="chack" id="d3" value="female">female<br>
<input type="file" name="image" action="image/*" ><br>
<input type="submit" name="sub" value="sign up" ><br>
</div>
</form>
<div id="output" ></div>
<script >
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "aform.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#output").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#output").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#output").html(e).fadeIn();
}
});
}));
});
</script>
</body>
</html>
Now here is the page where i am trying to send the form
<?php
print_r($_POST);
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
extract($_POST);
$hobby=implode(',','cric');
$img = $_FILES['iname']['name'];
$tmp = $_FILES['iname']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
$con=mysqli_connect("localhost","root","","users");
$qry="insert into abcd(username,password,email,hobby,gender,image)values('$uname','$pass','$email','$hobby','$chack','$image') ";
mysqli_query($con,$qry);
//print_r($run);
echo "<img src='$path' />";
}
}
else
{
echo 'invalid';
}
}
?>
What I am Doing Wrong can anyone Tell me about it?
I have implemented JCrop in my projects before in core PHP but when am trying to implement the same code in ZF2, its not working and i have added all the scripts and styles properly and they all are loaded, even the image is getting loaded but there is no selection box available to crop the image.
Suggesting a better way to implement the same functionality is welcome but it would be great if someone can tell me the reason for this not working.
here is the view script photo.phtml:
<?php
//adding javascripts specific to this page
$this->headScript()->appendFile($this->basePath('js/jquery.Jcrop.min.js'));
$this->headScript()->appendFile($this->basePath('js/jquery.min.js'));
$this->headScript()->appendFile($this->basePath('js/script.js'));
//adding stylesheets specific to this page
$this->headLink()->appendStylesheet($this->basePath('/css/Imageform_style.css'));
$this->headLink()->appendStylesheet($this->basePath('/css/jquery.Jcrop.min.css'));
?>
<section>
<div id="form_div">
<fieldset>
<legend><strong>Photograph</strong></legend>
<!--upload form-->
<form id="upload_form" enctype="multipart/form-data" method="post" 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" />
Step1: Please select image file
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler()" accept="image/*" />
<div class="error"></div>
<div class="step2">
<p style="">Step2: Please select a crop region </p>
<div><img id="preview"/></div>
<div id="image_details" class="info" style="display: none">
<p><label for="filesize">File size</label> <input type="text" id="filesize" name="filesize" ></p>
<p><label for="filetype">Type</label> <input type="text" id="filetype" name="filetype" ></p>
<p><label for="filedim">Dimension</label> <input type="text" id="filedim" name="filedim" ></p>
<p><label for="w">Width</label> <input type="text" id="w" name="w" ></p>
<p><label for="h">Height</label> <input type="text" id="h" name="h" ></p>
</div>
<div>
<input type="submit" value="Upload" name="upload" />
</div>
</div>
</form>
</fieldset>
</div>
</section>
script.js contains the functions required on this page.
// convert bytes into friendly format
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
// check for selected crop region
function checkForm() {
if (parseInt($('#w').val())) return true;
//$('.error').html('Please select a crop region and then press Upload').show();
alert('Please select a crop region and then press Upload');
return false;
};
// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#w').val(Math.round(e.w));
$('#h').val(Math.round(e.h));
};
// clear info by cropping (onRelease event handler)
function clearInfo() {
$('.info #w').val('');
$('.info #h').val('');
};
function fileSelectHandler() {
// $('#preview').src('');
// get selected file
var oFile = $('#image_file')[0].files[0];
// hide all errors
$('.error').hide();
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png|image\/gif)$/i;
if (! rFilter.test(oFile.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').show();
return;
}
// check for file size
if (oFile.size > 2048 * 1024) {
$('.error').html('You have selected too big file, please select a one smaller than 2 MB').show();
return;
}
// preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e) {
// e.target.result contains the DataURL which we can use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // onload event handler
// display step 2
$('.step2').fadeIn(500);
// display some basic image info
var sResultFileSize = bytesToSize(oFile.size);
$('#filesize').val(sResultFileSize);
$('#filetype').val(oFile.type);
$('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
// Create variables (in this scope) to hold the Jcrop API and image size
var jcrop_api, boundx, boundy;
// destroy Jcrop if it is existed
if (typeof jcrop_api != 'undefined')
jcrop_api.destroy();
// initialize Jcrop
$('#preview').Jcrop({
minSize: [32, 32], // min crop size
/// write code for changing the aspect ratio for signature file
aspectRatio : 0.75, // to keep aspect ratio 1:1, use 1
bgFade: true, // use fade effect
bgOpacity: .3, // fade opacity
onChange: updateInfo,
onSelect: updateInfo,
onRelease: clearInfo
}, function(){
// use the Jcrop API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the Jcrop API in the jcrop_api variable
jcrop_api = this;
});
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
And it was and still is working in my previous project.
EDIT:
Here is the generated HTML for this code in head
<link href="/Project1v3_zend/public/css/bootstrap.min.css" media="screen"
rel="stylesheet" type="text/css">
<link href="/Project1v3_zend/public/css/bootstrap-theme.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/Project1v3_zend/public/css/style.css" media="screen" rel="stylesheet" type="text/css">
<link href="/Project1v3_zend/public/css/Imageform_style.css" media="screen" rel="stylesheet" type="text/css">
<link href="/Project1v3_zend/public/css/jquery.Jcrop.min.css" media="screen" rel="stylesheet" type="text/css">
<link href="/Project1v3_zend/public/img/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon">
<!-- Scripts -->
<!--[if lt IE 9]><script type="text/javascript" src="/Project1v3_zend/public/js/html5shiv.js"></script><![endif]-->
<!--[if lt IE 9]><script type="text/javascript" src="/Project1v3_zend/public/js/respond.min.js"></script><![endif]-->
<script type="text/javascript" src="/Project1v3_zend/public/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/Project1v3_zend/public/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript" src="/Project1v3_zend/public/js/jquery.min.js"></script>
<script type="text/javascript" src="/Project1v3_zend/public/js/script.js"></script>
</head>
Seems like it should be :
$this->headScript()->appendFile($this->basePath('js/jquery.min.js'));
$this->headScript()->appendFile($this->basePath('js/jquery.Jcrop.min.js'));
$this->headScript()->appendFile($this->basePath('js/script.js'));
With jQuery being the first script to be appended? Since JCrop needs jQuery dependency to be satisfied?
Is there no console output in browser?
What does the generated html header for these scripts look like?
I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:
<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
<p><label for="image">Upload Image:</label>
<input type="file" id="imageUpload"/></p>
<p><button type="submit" class="button">Save</button></p>
<div id="preview">
<img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
</div>
</form>
and incorporated JS code/script below:
<script type="text/jaavascript">
$(document).ready(function(){
var thumb=$('#thumb');
new AjaxUpload('imageUpload',{
action:$('newHotnessForm').attr('action'),
name:'image',
onSubmit:function(file,extension){
$('#preview').addClass('loading');
},
onComplete:function(file,response){
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src',response);
}
});
});
There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
meVeekay's answer was good and am just making it more improvised by doing 2 things.
Check whether browser supports HTML5 FileReader() or not.
Allow only image file to be upload by checking its extension.
HTML :
<div id="wrapper">
<input id="fileUpload" type="file" />
<br />
<div id="image-holder"></div>
</div>
jQuery :
$("#fileUpload").on('change', function () {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
On input type=file add an event onchange="preview()"
For the function preview() type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>
#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#ImdID').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
img {
max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />
I'm trying to develop image crop using JQuery.
I use ajax to upload the image. after the image success fully uploaded. I load the uploaded image using jquery to its container.
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");
but the image selection doesnt work. why it could be happened ?
this is my code:
<style type="text/css">
#preview {
width: 150px;
height: 150px;
overflow: hidden;
}
</style>
<script type="text/javascript" src="<?php echo base_url()?>asset/jqupload/js/ajaxfileupload.js">
</script>
<script type="text/javascript" src="<?php echo base_url()?>asset/jcrop/jquery.Jcrop.pack.js">
</script>
<link rel="stylesheet" href="<?php echo base_url()?>asset/jcrop/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript">
function ajaxFileUpload(){
$("#loading").ajaxStart(function(){
$(this).show();
}).ajaxComplete(function(){
$(this).hide();
});
$.ajaxFileUpload({
url: '<?php echo site_url()?>/upload/do_upload',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
success: function(data, status){
if (typeof(data.error) != 'undefined') {
if (data.error != '') {
$("#image_upload").html(data.error);
$("#image_upload").fadeIn("slow");
}
else {
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");
$("#image_upload").fadeIn("slow");
$("#orig_h").val(data.width);
$("#orig_w").val(data.height);
//alert("<a href='" + data.path + "' />");
}
}
},
error: function(data, status, e){
$("#image_upload").html(e);
$("#image_upload").fadeIn("slow");
}
})
return false;
}
$(document).ready(function(){
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, $("#oring_w").val(), $("#oring_h").val()],
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 = $("#oring_w").val() / coords.w;
var ry = $("#oring_h").val() / coords.h;
$("#preview img").css({
width: Math.round(rx * $("#oring_w").val()) + 'px',
height: Math.round(ry * $("#oring_h").val()) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
});
</script>
<!-- begin main content -->
<div id="templatemo_content_area">
<h1 class="content_title">Label Info<hr/></h1>
<div id="templatemo_bi_full">
<h2>Label Setting</h2>
<div id="container">
</div>
<!--container-->
<br/>
<h2>Avatar</h2>
<div class="info">
</div>
<div id="avatar_container">
<form name="form" action="" method="POST" enctype="multipart/form-data">
<ul>
<li class="leftHalf ">
<label class="desc" for="lbl_type">
Change Your Avatar
</label>
<div>
<div id="avatar">
<img src="<?php echo $avatar?>" width="130" height="130" />
</div>
<div id="avatar_upload">
<input id="fileToUpload" name="fileToUpload" class="field field" value="" size="30" tabindex="5" type="file" /><input id="buttonUpload" name="buttonUpload" class="btTxt submit" type="submit" value="Upload" onclick="return ajaxFileUpload();"/><img id="loading" src="<?php echo base_url()?>asset/jqupload/images/loading.gif" style="display:none;">
</div>
</div>
</li>
</ul>
<ul id="crop_container">
<li class="leftHalf ">
<label class="desc" for="lbl_name">
Avatar for crop
</label>
<div id="image_upload">
<img src="<?php echo $avatar?>" width="450" height="130" id="cropbox" name="cropbox" />
</div>
</li>
<li class="rightHalf ">
<label class="desc" for="lbl_type">
Crop Display
</label>
<div id="preview">
<img src="<?php echo base_url() . 'files/' ?>" alt="thumb" />
</div>
</li>
<div class="info">
</div>
<li class="buttons ">
<input name="saveForm" class="btTxt submit" type="submit" value="Crop and Save" />
</li>
</ul>
<input type="text" id="x" name="x" />
<input type="text" id="y" name="y" />
<input type="text" id="w" name="w" />
<input type="text" id="h" name="h" />
<input type="text" id="oring_w" name="oring_w" />
<input type="text" id="oring_h" name="oring_h" />
</form>
</div>
<div class="cleaner">
</div>
</div>
<div class="cleaner">
</div>
</div>
<!-- end main content -->
Help me please ....
It doesn't work because you get your image via ajax call. When you call the jcrop function on document.ready the image doesn't exist. You need to put the jcrop code in the success function of the ajax call, after you add the image in DOM. Should be something like this (not tested):
$.ajaxFileUpload({
url: '<?php echo site_url()?>/upload/do_upload',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
success: function(data, status){
if (typeof(data.error) != 'undefined') {
if (data.error != '') {
$("#image_upload").html(data.error);
$("#image_upload").fadeIn("slow");
}
else {
$("#image_upload").html("<img src='" + data.path + "' width=\"460\" id=\"cropbox\" alt=\"cropbox\" />");//it is important to add the jcrop code after this line
$("#image_upload").fadeIn("slow");
$("#orig_h").val(data.width);
$("#orig_w").val(data.height);
$('#cropbox').Jcrop({
aspectRatio: 1,
setSelect: [0, 0, $("#oring_w").val(), $("#oring_h").val()],
onSelect: updateCoords,
onChange: updateCoords
});
}
}
},
error: function(data, status, e){
$("#image_upload").html(e);
$("#image_upload").fadeIn("slow");
}
})
None of the above worked for me .If you are also facing this issue try this
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: 1,
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
jcrop_api.setSelect([ 100,100,200,200 ]);
});
Or you could use .live function of the jQuery to add jCrop to any specified element (image) as soon as those are added to DOM.
Check this: http://api.jquery.com/live/