Cropping and uploading image with Croppie jquery plugin - javascript

cropping and uploading image using Croppie plugin working fine sample code as follows
<html lang="en">
<head>
<title>PHP and jQuery - Crop Image and Upload using Croppie plugin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
.croppie-container .cr-vp-circle
{
border-radius:0
}
.cr-slider-wrap
{
display:none
}
</style>
</head>
<body>
<div class="container">
<div class="card" style="max-height: 500px;">
<div class="card-header bg-info" style="display:none">PHP and jQuery - Crop Image and Upload using Croppie plugin</div>
<div class="card-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo"></div>
</div>
<div class="col-md-4" style="padding:5%;">
<strong>Select image to crop:</strong>
<input type="file" id="image">
<button class="btn btn-success btn-block btn-upload-image" style="margin-top:2%">Upload Image</button>
</div>
<div class="col-md-4" style="background: #9d9d9d;">
<div id="preview-crop-image" style="background: #fff;
width: 200px;
margin: 50px 72px;
height: 200px;"></div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var resize = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: { // Default { width: 100, height: 100, type: 'square' }
width: 200,
height: 200,
type: 'square' //square
},
boundary: {
width: 300,
height: 300
}
});
$('#image').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
resize.croppie('bind',{
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.btn-upload-image').on('click', function (event) {
resize.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (img) {
alert(img)
$.ajax({
url: "cropping.php",
type: "POST",
data: {"image":img},
success: function (data) {
html = '<img src="' + img + '" />';
$("#preview-crop-image").html(html);
}
});
});
});
</script>
</body>
</html>
But the result from croppie plugin is getting as canvas i.e base64 but we want the result from croppie plugin as same as file upload so that we can access the cropped image with $_FILES, how it can be achieved please suggest us.

Croppie is using canvas.drawImage(...) to manipulate images so you can not upload the images as you upload a file using a file input field. What you can do is, submit the base64 encoded string and reconstruct(base64 decode) the image in your server.
$imageName = $uuid.".png";
// extracting the base64 encoded string from the request payload
$imageArray = explode(";", $_POST['imagebase64']);
$imageContents = explode(",", $imageArray[1]);
$imagebase64 = base64_decode($imageContents[1]);
// saving the image to a temp file
$tempPath = sys_get_temp_dir()."/".$imageName;
file_put_contents($tempPath, $imagebase64);
Now you have the uploaded image saved in $tempPath

Related

How to use Cropper.js with images that are already uploaded to my server instead of cropping and then uploading image to correct folder

Hi I'm new to Js so not really sure how to figure this one out. I have a user pictures gallery on my website and I use simple php file upload script to upload pictures for my users. I have a button under each picture to set given image as a profile pic but I'm in need of getting this picture cropped to correct aspect ratio so I tried using Cropper.js. The problem is I can't find a way to pass an image to cropper.js. else than creating an upload form. I've spent days trying to google the way I could use cropperjs without this upload form but can't seem to find a way. It's my first question on stackoverflow any help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<title>PHP Crop Image Before Upload using Cropper JS</title>
<meta name="_token" content="{{ csrf_token() }}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha256-WqU1JavFxSAMcLP2WIOI+GB2zWmShMI82mTpLDcqFUg=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" integrity="sha256-jKV9n9bkk/CTP8zbtEtnKaKf+ehRovOYeKoyfthwbC8=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js" integrity="sha256-CgvH7sz3tHhkiVKh05kSUgG97YtzYNnWt6OXcmYzqHY=" crossorigin="anonymous"></script>
</head>
<style type="text/css">
img {
display: block;
max-width: 100%;
}
.preview {
overflow: hidden;
width: 160px;
height: 160px;
margin: 10px;
border: 1px solid red;
}
.modal-lg{
max-width: 1000px !important;
}
</style>
<body>
<div class="container">
<h1>PHP Crop Image Before Upload using Cropper JS - NiceSnippets.com</h1>
<form method="post">
<input type="file" name="image" class="image">
</form>
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">PHP Crop Image Before Upload using Cropper JS - NiceSnippets.com</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<div class="row">
<div class="col-md-8">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
<div class="col-md-4">
<div class="preview"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var $modal = $('#modal');
var image = document.getElementById('image');
var cropper;
$("body").on("change", ".image", function(e){
var files = e.target.files;
var done = function (url) {
image.src = url;
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$("#crop").click(function(){
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
canvas.toBlob(function(blob) {
url = URL.createObjectURL(blob);
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
$.ajax({
type: "POST",
dataType: "json",
url: "upload.php",
data: {image: base64data},
success: function(data){
console.log(data);
$modal.modal('hide');
alert("success upload image");
}
});
}
});
})
</script>
</body>
</html>

CROPPER JS Get cropper canvas not working with larger files

I am using https://github.com/fengyuanchen/cropperjs/ but it has a problem in getCroppedCanvas function ,
It's working just fine with small images but not showing when it comes to larger images
result.appendChild(cropper.getCroppedCanvas());
I am using this live example https://fengyuanchen.github.io/cropperjs/examples/upload-cropped-image-to-server.html; source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/cropper.css">
<style>
.label {
cursor: pointer;
}
.progress {
display: none;
margin-bottom: 1rem;
}
.alert {
display: none;
}
.img-container img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Upload cropped image to server</h1>
<label class="label" data-toggle="tooltip" title="Change your avatar">
<img class="rounded" id="avatar" src="https://avatars0.githubusercontent.com/u/3456749?s=160" alt="avatar">
<input type="file" class="sr-only" id="input" name="image" accept="image/*">
</label>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
<div class="alert" role="alert"></div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Crop the image</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="img-container">
<img id="image" src="https://avatars0.githubusercontent.com/u/3456749">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="crop">Crop</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
<script src="https://fengyuanchen.github.io/cropperjs/js/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar');
var image = document.getElementById('image');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
$alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (URL) {
done(URL.createObjectURL(file));
} else if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
};
reader.readAsDataURL(file);
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 160,
height: 160,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob, 'avatar.jpg');
$.ajax('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function () {
$alert.show().addClass('alert-success').text('Upload success');
},
error: function () {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
},
complete: function () {
$progress.hide();
},
});
});
}
});
});
</script>
</body>
</html>
the cropper script is in: https://fengyuanchen.github.io/cropperjs/js/cropper.js
Using croppiejs helped me solve this issue. To utilize Croppie with a preview, you just set the value of an html image element to croppie's base64 result:
First create croppie instance:
var cropperlg = new Croppie(document.getElementById('croppie-lg'), {
viewport: {
width: 400
height: 800
},
boundary: {
height: 500
width: 1000
}
});
This bit of code binds croppie to an image and executes the crop on click.
EDIT: I simplified the code for a more basic example.
cropperlg.bind({
url: '/images/someimg.jpg'
});
$('#crop-btn').on('click', (e) => {
cropperlg.result({
type: 'canvas',
size: { width: 1000, height: 400 }
}).then(function(result) {
$('#cropped-img').attr('src', result);
})
});
You should be able to figure it out from here.
this worked for me
var cropper = $('#cropper-image').cropper('getCroppedCanvas', {
// Limit max sizes
maxWidth: 4096,
maxHeight: 4096,
});
After setting this, it worked well on both mobile and desktop.

jquery preview image not working

So I'm trying to implement a preview button so that when my users clicks on the upload button image they could have a preview but the thing is that it is not working, I wonder why ?? A brief description : I have a js function that creates new elements and append it to a p tag date. It is in this function that is going to create the preview image code
// code for creating new elements
function createElements(){
const userQuestions = document.querySelector('#userQuestions');
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="$(\'#filePhoto\').click()"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" /></center><div class="grid-container">'
);
}
///Code to preview image
function handleImage(e) {
var imageLoader = document.getElementById('filePhoto');
imageLoader.addEventListener('change', handleImage, false);
var reader = new FileReader();
reader.onload = function (event) {
$('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' );
}
reader.readAsDataURL(e.target.files[0]);
}
.uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>
If you run the snippet above you can see that the button is woeking but the preview is not showing. Could someone help me?
HTML:
<div class="row">
<div class="col-xs-4">
<div class="form-group">
<label>Company Logo</label>
<input type="file" class="form-control" value="" name="companyLogo" id="companyLogo" accept="image/*" />
</div>
</div>
<div id="displayImage">
<img id="imgData" src="#" alt="your image" height="150px" width="150px" />
</div>
</div>
JavaScript:
$("#companyLogo").change(function(e) {
if(e.target.value === "") {
$("#displayImage").hide();
} else {
$("#displayImage").show();
}
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#imgData").attr("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
Short n simple
No need to create an element on click.
Just add an image tag and set a default image like no image selected or something like that.
The following code will help you
<input type="file" name="myCutomfile" id="myCutomfile"/>
<img id="customTargetImg" src="default.jpg" width="400" height="250">
$("#myCutomfile").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#customTargetImg').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
Take advantage of jQuery -- particularly using
event handlers
delegated event handlers for dynamically-created elements
tree traversal methods.
$(function() {
var userQuestions = $('#userQuestions');
// create onclick event handler for your button
$('#addElements').click(function() {
// IDs must be unique - since you can have an arbitrary number of filePhoto, use a class instead
userQuestions.append(
'<div class="uploader"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" class="filePhoto" /><div class="grid-container"></div>'
);
});
// create delegated onclick event handler for your .uploader
userQuestions.on('click', '.uploader', function() {
// you only want to target the file input immediately after it
$(this).next('[type=file]').click();
});
// create delegated onchange event handler for your .filePhoto
userQuestions.on('change', '.filePhoto', function() {
// find related uploader
var uploader = $(this).prev('.uploader');
// check file was given
if (this.files && this.files.length) {
var reader = new FileReader();
reader.onload = function(event) {
uploader.html('<img width="300px" height="350px" src="' + event.target.result + '"/>');
}
reader.readAsDataURL(this.files[0]);
}
});
});
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<!-- added ID attribute -->
<button type="button" id="addElements">add elements</button>
</body>
</html>
Edit
This answer is a non-jQuery solution based off your comment.
// code for creating new elements
function createElements() {
// no need to document.querySelector if the selector is an ID
const userQuestions = document.getElementById('userQuestions');
// you want to use onclick/onchange attributes here as they are dynamically created
userQuestions.insertAdjacentHTML(
'beforeend', '<div class="uploader" onclick="selectFile(this)"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" onchange="handleImage(this)" />'
);
}
// trigger click on file input that follows the uploader
function selectFile(uploader) {
uploader.nextSibling.click();
}
///Code to preview image
function handleImage(input) {
if (input.files.length) {
var reader = new FileReader();
reader.onload = function(e) {
input.previousSibling.innerHTML =
'<img width="300px" height="350px" src="' + e.target.result + '"/>';
}
reader.readAsDataURL(input.files[0]);
}
}
.uploader {
width: 50%;
height: 35%;
background: #f3f3f3;
border: 2px dashed #0091ea;
}
.filePhoto {
display: block;
width: 185px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>

Using Javascript to remove the text from the image?

Using cropper.js I could crop/resize the image, but is there any way I could, for example, remove the text from the image? or drawing? Then save or download?
Thanks for any help
https://jsfiddle.net/dalinhuang/dsh33tu8/
$('#edit_img').click(function(){
$('#image').cropper({
aspectRatio: 'auto',
crop: function(e) {
}
});
});
$("#reset").click(function() {
$('#image').cropper("reset");
});
/* Limit image width to avoid overflow the container */
img {
max-width: 100%; /* This rule is very important, please do not ignore this! */
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/3.0.0/cropper.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/3.0.0/cropper.min.js"></script>
<button id="edit_img">EDIT IMG</button><br><br>
<button id="reset">RESET</button><br><br>
<div>
<img id="image" src="https://s3.amazonaws.com/dev-resized-image/full/dad3b2b5-1d74-4277-8ee7-fc11196a508c/funny-that-look-pictures-lol.jpg">
</div>
Finally after few days of searching.
Turns out this is the best. Using Adobe API to edit images!!!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Load Feather code -->
<script type="text/javascript" src="https://dme0ih8comzn4.cloudfront.net/imaging/v3/editor.js"></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'your-api-key-here',
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'all',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
<div id='injection_site'></div>
<!-- Add an edit button, passing the HTML id of the image and the public URL of the image -->
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor('image1', 'https://i.imgflip.com/ehl86.jpg');" /></p>
<img id='image1' src='https://i.imgflip.com/ehl86.jpg'/>

Make a Div and it's Child Element's an Image in Javascript

I have this layout in HTML:
<div id="front">
<img id="student_front" src="' . $path . '/images/student_front.jpg"></img>
<img id="myid_info_photo"></img>
<div id="myid_info_college">CEIT</div>
<div id="myid_info_idnumber">101-03043</div>
<img id="myid_info_signature"></img>
<div id="myid_info_course">BSCS</div>
<div id="myid_info_name">Alyssa E. Gono</div>
<div id="myid_info_barcode"></div>
</div>
I want to generate a Jpeg file of what div#front will appear in my screen. How will I do that in Javascript? I have a button that will invoke an action when it is click.
function myid_print_id() {
win = window.open(document.getElementById("student_front").src,"_blank");
win.onload = function() {
win.print();
}
}
$('#myid_print_id').on('click', function(e) {
e.preventDefault();
myid_print_id();
});
myid_print_id() function just retrieves the image file. I wanted to retrieve the appearance of my whole div with an id "front".
Load the html2canvas js file, then add this:
$('#btn').click(function() {
html2canvas($('#front'), {
onrendered: function(canvas) {
myImage = canvas.toDataURL("image/png");
$('#output').append(canvas);
}
});
});
#output {
border: 1px solid #888888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<div id="front">
<img id="student_front" src="http://lorempixel.com/400/200">
<div id="myid_info_college">CEIT</div>
<div id="myid_info_idnumber">101-03043</div>
<div id="myid_info_course">BSCS</div>
<div id="myid_info_name">Alyssa E. Gono</div>
<div id="myid_info_barcode">More text</div>
</div>
<button id="btn">CLICK FOR PIC</button>
<br>
<div id="output"></div>
You will need to change the image URL to something on the same domain (html2canvas does not load cross domain images).
Html
<div>
<input type="button" id="btnGenerateImage" value="Generate Image" />
</div>
<div>
<canvas id="myCanvas"></canvas>
</div>
<div>
<h1>
Generated Content</h1>
<img id="canvasImg" alt="Right click to save me!">
</div>
SCRIPT
$("#btnGenerateImage").on('click', function () {
var canvas = document.getElementById('myCanvas');
// save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
// set canvasImg image src to dataURL
// so it can be saved as an image
document.getElementById('canvasImg').src = dataURL;
});

Categories