Ajax Cropped Image to PHP - javascript

I am trying to create a jQuery image cropper. A user will upload an image and an image preview of where they want to crop will be shown. The cropping size should be exactly 600 x 400. So if the user tries to upload an image that's 2000px wide by 2000px tall, then they will only be able to get a 600 x 400 selection of that image. After the user has selected their crop of that image, then they will be able to upload it. The cropped image should be relayed in Ajax and sent to PHP, but how do I create the Ajax for it? How can I send the cropped coordinates and the image dimensions through Ajax to PHP? Afterwards, how should the PHP look like? This plugin (cropbox) works on getting src's of images, but it's not working with input type="file" for some reason. Here's the jsfiddle, and here's what I've tried:
HTML
<input type="file" id="cropimage">
jQuery
$(function() {
var file = $("#cropimage").files[0];
if (file.type.match(/image\/.*/)) {
var reader = new FileReader();
reader.onload = function() {
var $img = $('<img />').attr({
src: reader.result
});
}
$img.on('load', function() {
$img.cropbox({
width: 600,
height: 400
}).on('cropbox', function(event, results, img) {
})
})
}
})

Attach change listener over file-input
Set reader.readAsDataURL(file);
Append $img in DOM
$(function() {
$("#cropimage").on('change', function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function() {
var $img = $('<img />').attr({
src: reader.result
});
$img.on('load', function() {
$img.cropbox({
width: 600,
height: 400
}).on('cropbox', function(event, results, img) {});
});
$('body').append($img);
};
reader.readAsDataURL(file);
});
});
Fiddle Demo

Related

How to get image dimension in Dropzone JS with setting createImageThumbnails to false?

With Dropzone.js, I am trying to get image height and width with createImageThumbnails = false. To be more precise, I do not need thumbnails to be created while dropping images because the process becomes slow specially when I drop many images at once. I just need to scan height and width of all images that are dropped and save them into a database. But the problem is, when I turn off thumbnail creation, dropzone does not provide image height and width. As per documentation, image height and width are provided after the thumbnail event is triggered. So, quite the opposite to what I need. So as a solution, I would like to be able to get image height and width info as soon as images are dropped into dropzone and there should be no delay for creating thumbnail. Please advise if there is a way out of it.
HTML
<div id="dropzone">
<form class="dropzone" id = "upload-widget" action = "/demo">
</form>
</div>
JS
jQuery(document).ready(function($)
{
var images = Array();
var item = [];
Dropzone.options.uploadWidget = {
autoProcessQueue: false,
acceptedFiles: 'image/*',
previewTemplate: '<div class="dz-filename"><span data-dz-name></span></div>',
createImageThumbnails: false,
init: function() {
this.on("addedfile", function(file)
{
height = file.height;
width = file.width;
item = {Name : file.name, Size:file.size, Height:file.height, Width:file.width};
images.push(item);
});
}
};
});
You could try working with the accept function, along with FileReader(), and the Image() constructor.
Dropzone.options.uploadWidget = {
autoProcessQueue: false,
acceptedFiles: 'image/*',
previewTemplate: '<div class="dz-filename"><span data-dz-name></span></div>',
createImageThumbnails: false,
accept: function(file, done) {
// FileReader() asynchronously reads the contents of files (or raw data buffers) stored on the user's computer.
var reader = new FileReader();
reader.onload = (function(entry) {
// The Image() constructor creates a new HTMLImageElement instance.
var image = new Image();
image.src = entry.target.result;
image.onload = function() {
console.log(this.width);
console.log(this.height);
};
});
reader.readAsDataURL(file);
done();
}
}

cropper.jscant initialize blob image <img>tag by blueimp

So what i want :
select an image with input type file,
downscale with blueimp,
crop that image with cropper.js
so the blueimp part is working fine, the image gets resized to maxWidth property and is appended as <img> tag to "#imagearea" then i want to initialize cropper.js based on that tag, like in the docs, heres my code
document.getElementById('file-input').onchange = function (e) {
var loadingImage = loadImage(
e.target.files[0],
function (img) {
$(img).attr("style","max-width: 100%;")
$('#imagearea').append(img)
// now i see the image and when i inspect dom its a <img> tag
// so lets initialize the cropper
$('#imagearea').find("img").cropper({
aspectRatio: 16 / 9,
crop: function(e) {
}
});
},
{maxWidth: 1280}
);
};
but when initializing the cropper,
first i get an 404 error like
GET blob:http://foo.bar/64c77709-29f7-44ba-8772-49517e7976e5 404 (Not Found)
and then
Uncaught RangeError: Offset is outside the bounds of the DataView
at DataView.getUint8 ()
at m (6eaf333.js:7051)
at e.value (6eaf333.js:7051)
at XMLHttpRequest.n.onload (6eaf333.js:7051)
Please use "noRevoke " option.
document.getElementById('file-input').onchange = function (e) {
var loadingImage = loadImage(
e.target.files[0],
function (img) {
$(img).attr("style","max-width: 100%;")
$('#imagearea').append(img)
// now i see the image and when i inspect dom its a <img> tag
// so lets initialize the cropper
$('#imagearea').find("img").cropper({
aspectRatio: 16 / 9,
crop: function(e) {
}
});
},
{maxWidth: 1280,noRevoke: true}
);
};

Validating Image upload

I'm trying to validate the image before being uploaded. I restrict the size and pixels but the problem is that I can still upload the image even though it doesn't apply to the restrictions. How can I stop the user or disable the upload as this validation is done with the onchange command.
var myFile = document.getElementById('file');
myFile.addEventListener('change', function() {
image = new Image();
if(this.files[0].size > 800000)
{
alert("File size too big. Please upload a smaller image");
return false;
}
else
{
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(this.files[0]);
reader.onload = function (e)
{
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function () {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
if (height > 500 || width > 375) {
alert("Height and Width must not exceed 500px(h) and 375px(w).");
return false;
}
else
{
alert("Uploaded image has valid Height and Width.");
return true;
}
};
}
}
});
You can reset the value of the file input element if your validation fails
var myFile = document.getElementById('file');
...
myFile.value=""
And then show validation to the user in page.
Here's what I did as an alternative. I didn't know this was possible until I came upon this. You just add this to the relevant alert/return false section and it disables the submit button.
jQuery("input[type='submit']").attr("disabled", 'disabled');

drag and drop images from `dropbox` account to html canvas - `not working in chrome`

This code is to drag images from image gallery and drop inside canvas (fabric.js is used) and also drag and drop images from dropbox account which is opend in another tab. This works fine in firefox, I can drag images from my drop box account and drop in inside canvas. But not in chrome. e.dataTransfer.getData("Text") gives an empty value in chrome. I thought it's a problem of same-origin-policy and tried a lot to fix it. But no luck. Please help me to get a work around for this.
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
// handle local images
if(e.dataTransfer.files.length > 0){
var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (f.type.match('image.*')) {
// Read the File objects in this FileList.
var reader = new FileReader();
// listener for the onload event
reader.onload = function(evt) {
// create img element
var img = document.createElement('img');
img.src= evt.target.result;
// put image on canvas
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
};
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
}
// handle dropbox images
else{
var img = e.dataTransfer.getData("Text");
console.log(img);
var img = e.dataTransfer.getData("Text");
if (img.indexOf('jpg')>0 ||img.indexOf('png')>0){
var temp = '<img draggable="true" src="'+img+'" width="250" height="250"></img>';
$('#before').append(temp);
var i = document.querySelector('img[src="'+img+'"]');
console.log('i: ',i);
var nI = new fabric.Image(i,{
width: i.width,
height:i.height,
left:e.layerX,
top:e.layerY
});
canvas.add(nI);
}
}
return false;
}

Add image from user computer to canvas

i'm working on a web app that allow users to create dynamic slideshow. Currently i've got an issue regardless how to add image from the computer's user to the canvas.
I'm using a input button to get the file from the computer and it appeal a function who will add the image to the canvas.
So far i've tried different ways to add the image to the canvas as well as this one : Dynamically add image to canvas
But the code showing here doesnt work in my case, because it just draw the image into the canvas but it wont allow it to be draggable and resizable just like the Kitchensink.js demo from Fabricsjs.
I've also try to convert the image into Base64 and use the LoadJSON to convert it back but i encountered this error :
Uncaught TypeError: Cannot read property 'length' of undefined fabric.js:2089
enlivenObjects fabric.js:2089
fabric.util.object.extend._enlivenObjects fabric.js:9025
fabric.util.object.extend.loadFromJSON fabric.js:8953
sub
Sub's refering to the function i've called to add the image.
I've also try this code :
document.getElementById('imgLoader').onchange = function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new fabric.Image();
img.onload = function(){
img.set({
left : 250,
top : 250,
angle : 20,
padding: 10,
cornersize: 10
});
image.scale(getRandomNum(0.1, 0.25)).setCoords();
canvas.add(image);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
Which catch these errors :
Uncaught TypeError: Cannot read property 'width' of undefined fabric.js:14358
fabric.Image.fabric.util.createClass._setWidthHeight fabric.js:14358
fabric.Image.fabric.util.createClass._initConfig fabric.js:14334
fabric.Image.fabric.util.createClass.setElement fabric.js:14127
fabric.Image.fabric.util.createClass._initElement fabric.js:14322
fabric.Image.fabric.util.createClass.initialize fabric.js:14097
(anonymous function) fabric.js:2679
klass fabric.js:2728
reader.onload diapo.js:746
I've cleary run out of ideas and only achieved to draw the image but not adding it to the canvas.
All in one i'd like to add an image to my Fabricjs canvas with the same attributes regardless the draggable as the Kitchensink demo.
Thanks in advance for your help :)
There is one basic mistake in your code, you are trying to add the image data to the src attribute of the fabric.Image object.
What you need to do, is to create an Image object with your result, and pass it to the fabric.Image object, like this:
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
var image = new fabric.Image(imgObj);
}
I made a working example here:
http://jsfiddle.net/jaibuu/Vp6wa/
Upload image in canvas from computer by Fabric js.
var canvas = new fabric.Canvas('canvas');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({left: 0, top: 0, angle: 00,width:100, height:100}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({format: 'png', quality: 0.8});
});
};
reader.readAsDataURL(file);
});
canvas{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="canvas" width="450" height="450"></canvas>

Categories