I want to use Jquery Croppie Plugin on my site to crop image for my user but I've got this problem the code that i write not show as an example in Croppie Site
Here's my code
HTML code
<input type="file" id="upload" value="Choose a file">
<button class="upload-result">Result</button>
<div class="upload-msg">
Upload a file to start cropping
</div>
<div id="upload-demo"></div>
JS code
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
NB : I have link my site with jquery, croppie.js and croppie.css
Try it, it works for me.
I used PHP to save the image.
<?php
if(isset($_POST['imagebase64'])){
$data = $_POST['imagebase64'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('image64.png', $data);
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Test</title>
<link href="croppie.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="croppie.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
var $uploadCrop;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
});
$('.upload-demo').addClass('ready');
}
reader.readAsDataURL(input.files[0]);
}
}
$uploadCrop = $('#upload-demo').croppie({
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () { readFile(this); });
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'original'
}).then(function (resp) {
$('#imagebase64').val(resp);
$('#form').submit();
});
});
});
</script>
</head>
<body>
<form action="test-image.php" id="form" method="post">
<input type="file" id="upload" value="Choose a file">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
Send
</form>
</body>
</html>
a JSFiddle link
Related
I am trying to crop image and send the cropped data to server side. I am using imgareaselect plugin. I get the coordinates of selection but could not crop the image. All the solutions available on internet is to preview cropped image using css. But how can I get the cropped data? No need of preview the cropped image. My code is
cropw = $('#cropimg').imgAreaSelect({
maxWidth: 300, maxHeight: 300,
aspectRatio: '1:1',
instance: true,
handles: true,
onSelectEnd: function (img, selection) {
x1 = selection.x1;
y1 = selection.y1;
x2 = selection.x2;
y2 = selection.y2;
}
});
Hey #Shahbaz I was trying out a solution for you using cropper.js.
This is what you can do
Download cropper.js from here
//link the js files
<head>
<script src="jquery.js"></script> // optional
<link href="cropper.min.css" rel="stylesheet">
<script src="cropper.min.js"></script>
</head>
Body
<input type="file" name="image" id="image" onchange="readURL(this);"/>
<div class="image_container">
<img id="blah" src="#" alt="your image" />
</div>
<div id="cropped_result"></div> // Cropped image to display (only if u want)
<button id="crop_button">Crop</button> // Will trigger crop event
Javascript
<script type="text/javascript" defer>
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]);
setTimeout(initCropper, 1000);
}
}
function initCropper(){
var image = document.getElementById('blah');
var cropper = new Cropper(image, {
aspectRatio: 1 / 1,
crop: function(e) {
console.log(e.detail.x);
console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl = cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
/* ---------------- SEND IMAGE TO THE SERVER-------------------------
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
----------------------------------------------------*/
})
}
</script>
Hope this helps. Thanks.
Added this one based on the accepted answer, In case anyone is using the jquery wrapper for cropper
let ICropper = (function($) {
let $cropperCanvasImage = $('#cropper-canvas-image');
return {
readUrl,
cropImage
}
function readUrl(input) {
if (input.files && input.files[0]) {
let reader = new FileReader();
reader.onload = function(e) {
$cropperCanvasImage.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
}
function initCropper() {
$cropperCanvasImage.cropper({
aspectRatio: 1 / 1
});
}
function cropImage() {
let imgUrl = $cropperCanvasImage.data('cropper').getCroppedCanvas().toDataURL();
let img = document.createElement("img");
img.src = imgUrl;
$("#cropped-result").append(img);
}
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script name="jquery-croper-script">
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(require("jquery"),require("cropperjs")):"function"==typeof define&&define.amd?define(["jquery","cropperjs"],r):r(e.jQuery,e.Cropper)}(this,function(c,s){"use strict";if(c=c&&c.hasOwnProperty("default")?c.default:c,s=s&&s.hasOwnProperty("default")?s.default:s,c.fn){var e=c.fn.cropper,d="cropper";c.fn.cropper=function(p){for(var e=arguments.length,a=Array(1<e?e-1:0),r=1;r<e;r++)a[r-1]=arguments[r];var u=void 0;return this.each(function(e,r){var t=c(r),n="destroy"===p,o=t.data(d);if(!o){if(n)return;var f=c.extend({},t.data(),c.isPlainObject(p)&&p);o=new s(r,f),t.data(d,o)}if("string"==typeof p){var i=o[p];c.isFunction(i)&&((u=i.apply(o,a))===o&&(u=void 0),n&&t.removeData(d))}}),void 0!==u?u:this},c.fn.cropper.Constructor=s,c.fn.cropper.setDefaults=s.setDefaults,c.fn.cropper.noConflict=function(){return c.fn.cropper=e,this}}});
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css" />
<input type="file" name="source-image" id="sourceImage" onchange="ICropper.readUrl(this);" />
<div class="image-container">
<img id="cropper-canvas-image" src="#" alt="your image" />
</div>
<div id="cropped-result"></div>
<button onclick="ICropper.cropImage(this)">Crop</button>
Did you try using a crop plugin for Jquery, like:
https://fengyuanchen.github.io/cropper/
You have to import the scripts in your page:
<?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']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://deepliquid.com/Jcrop/js/jquery.Jcrop.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.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('Selecione a área para recorte.');
return false;
};
</script>
</head>
<body>
<div id="outer">
<div class="jcExample">
<div class="article">
<h1>Crop jQuery</h1>
<img src="demo_files/pool.jpg" id="cropbox" />
<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>
</div>
</div>
</div>
</body>
</html>
Croppie uses a DIV container and not a CANVAS to do its cropping. I am trying to find out how to save the resulting cropped image from this DIV to a directory on the Server, such as via a SAVE button.
Here is my HTML code ...
<!-- begin snippet: js hide: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<head>
<title>Demo Croppie</title>
<link rel="Stylesheet" type="text/css" href="css/croppie.css" />
<link rel="Stylesheet" type="text/css" href="css/sweetalert.css" />
</head>
<body>
<div id="testCanvas"></div>
<div class="actions" style="margin-left: auto; margin-right: auto; width:250px;">
<button class="vanilla-result">Result</button>
<button class="vanilla-rotate" data-deg="-90">Rotate Left</button>
<button class="vanilla-rotate" data-deg="90">Rotate Right</button>
</div>
<p><button onclick="function();">Save</button></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/croppie.js"></script>
<script src="js/demo.js"></script>
<script src="js/sweetalert.min.js"></script>
<script>
Demo.init();
</script>
</body>
</html>
Here is my JavaScript configurations ...
function demoVanilla() {
var vanilla = new Croppie(document.getElementById('testCanvas'), {
viewport: { width: 300, height: 300, type: 'square' },
boundary: { width: 350, height: 350 },
enableOrientation: true
});
vanilla.bind({
url: 'imgs/demo-1.jpg',
orientation: 1
});
document.querySelector('.vanilla-result').addEventListener('click', function (ev) {
vanilla.result('canvas').then(function (src) {
popupResult({
src: src
});
});
});
$('.vanilla-rotate').on('click', function(ev) {
vanilla.rotate(parseInt($(this).data('deg')));
});
}
The rest comes by default without changes from Croppie at https://github.com/Foliotek/Croppie such as demo.js, etc.
Here is an example on how to make a download button. If you figure out how this works, then you just need to replace the <a>link with for a <form> with a submit button,
var vanillaResult = document.querySelector('.vanilla-result'),
vanillaSave = document.querySelector('.vanilla-save'),
vanillaRotate = document.querySelector('.vanilla-rotate');
function demoVanilla() {
var vanilla = new Croppie(document.getElementById('vanilla-demo'), {
viewport: {
width: 100,
height: 100
},
boundary: {
width: 300,
height: 300
},
enableOrientation: true
});
vanilla.bind({
url: 'http://foliotek.github.io/Croppie/demo/cat.jpg',
orientation: 1
});
vanillaResult.addEventListener('click', function() {
vanilla.result('canvas').then(resultVanilla);
});
vanillaSave.addEventListener('click', function() {
vanilla.result('canvas').then(saveVanilla);
});
vanillaRotate.addEventListener('click', function() {
vanilla.rotate(parseInt($(this).data('deg')));
});
}
function resultVanilla(result) {
swal({
title: '',
html: true,
text: '<img src="' + result + '" />',
allowOutsideClick: true
});
}
function saveVanilla(result) {
swal({
title: '',
html: true,
text: '<a id="save" href="' + result + '" download="result"><img src="' + result + '" /><br><button>Download</button></a>',
showConfirmButton: false,
showCancelButton: true,
allowOutsideClick: true,
});
}
demoVanilla();
body {
min-width: 360px;
}
.actions {
width: 300px;
margin: 0 auto;
}
<!DOCTYPE html>
<html>
<head>
<title>Demo Croppie</title>
<link rel="Stylesheet" type="text/css" href="http://foliotek.github.io/Croppie/croppie.css" />
<link rel="Stylesheet" type="text/css" href="http://t4t5.github.io/sweetalert/dist/sweetalert.css" />
</head>
<body>
<div id="vanilla-demo"></div>
<div class="actions">
<button class="vanilla-result">Result</button>
<button class="vanilla-save">Save</button>
<button class="vanilla-rotate" data-deg="-90">Rotate Left</button>
<button class="vanilla-rotate" data-deg="90">Rotate Right</button>
</div>
<div id="result"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://foliotek.github.io/Croppie/croppie.js"></script>
<script src="http://t4t5.github.io/sweetalert/dist/sweetalert-dev.js"></script>
</body>
</html>
GOT IT!
Thanks to one of the developers of Croppie "thedustinsmith" and "TWFPSP" for directing me to the right eternal resources and their offered info.
$( document ).ready(function() {
vanillaRotate = document.querySelector('.vanilla-rotate');
var $uploadCrop = $('#upload-demo');
$uploadCrop.croppie({
viewport: {
width: 250,
height: 250,
type: 'square'
},
boundary: {
width: 300,
height: 300
}
});
$uploadCrop.croppie('bind', 'imgs/cat.jpg');
vanillaRotate.addEventListener('click', function() {
vanilla.rotate(parseInt($(this).data('deg')));
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'original'
}).then(function (resp) {
$('#imagebase64').val(resp);
$('#form').submit();
});
});
});
HTML body ...
<form action="test-image.php" id="form" method="post">
<div id="upload-demo"></div>
<input type="hidden" id="imagebase64" name="imagebase64">
Send
</form>
<button class="vanilla-rotate" data-deg="-90">Rotate</button>
test-image.php ...
<?php
if(isset($_POST['imagebase64'])){
$data = $_POST['imagebase64'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('image64.png', $data);
}
?>
Now the rotate function is not working and I am trying to fix it. Seem to not know how to include the orientation configs in this setting which is different than the demoUpload where it is illustrated in the demo file. But at least the saving to the server works great.
here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.
I have a upload button on my webpage. Whenever I upload an image it will show a preview of the image(s) that were uploaded. If more than one image is uploaded, the previews of the second image will be shown next to the first and so on.
I need to be able to upload all the shown images into my uploads folder using PHP. How can I do this?
This is my HTML code that will upload the images one by one and show preview:
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
var blank = "http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
</script>
<style>
img {
height:200px ! important;
width:200px ! important;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function() {
$('input[type="file"]').change(function() {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
//console.log(file.width);
var reader = new FileReader();
var img = new Image();
var _URL = window.URL || window.webkitURL;
reader.readAsDataURL(file);
reader.onload = function(_file) {
// Create a container for image and span X
$imageItem = $('<div style=" float: left; border:5px solid gray; ">').addClass('imageItem');
$(img).appendTo($imageItem);
$('<span>').html('<a href="#" style=" z-index: 1; margin-left: -32px;"><img src="trash.png" title="remove" style=" width: 32px ! important;height: 32px ! important;">
</a>').addClass('remover').appendTo($imageItem);
img.src = _file.target.result;
// Append the container to panel
$('#previewPane').append($imageItem);
//console.log(img.src);
console.log(img.width);
}
}
// Deletegate for dynamically created span, so we don't have to register a
// new event listener each time a new imageContainer is created.
$('#previewPane').on('click', '.remover', function() {
$this = $(this);
$this.parent('.imageItem').remove();
});
});
}); //]]>
</script>
</head>
<body>
<section>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type='file' name="file[]" id="file_select" multiple="multiple" />
<br/> <span id="previewPane"></span>
<input type="submit" value="OK">
</form>
</section>
</body>
</html>
This is my PHP code but currently it is uploading only one image.
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "uploads/" . $_FILES['file']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}
?>
When the page is loaded, the image specified in src is displayed.When a user clicks on the form to upload the image,everything works fine except the image on the page does not change.
It is because when the user clicks on the form to upload the image, he is directed to php file 2 but from there there is no request to change the image in php file 1. How can I achieve this (using ajax and jquery)?
Try this code. This is the core.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#imgInp').on('change', function() {
readPath(this);
});
});
function readPath(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>
</head>
<body>
<form id="form1">
<input type='file' id="imgInp" />
<img id="blah" src="#" width="500px" height="200px" alt="your image" />
</form>
</body>
</html>
Here is another code snippet. Check your conditions in the server part and don't forget provide the locations correctly in server side and image src.
HTML Part
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<img id="blah" src="#" width="500px" height="200px" alt="your image" />
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#blah").attr("src",response.responseText);
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
Upload.php
<?php
//upload.php
$output_dir = "C:/wamp/www/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo $_FILES["myfile"]["name"];
}
}
?>