Image dropping

2012-02-26

Simple image dropping-rescaling-ajaxing shim. Don't remember where exactly I got the original from, but I suppose that doesn't matter. It's pretty generic. You can drop an image on the target element. It will scale the image down to a certain size. Then it takes the result, turns it into a dataURL, cuts off the image type part and sends it off to a server. Good luck with it.

Code:
var drop = div.querySelector('.image-drop');
drop.ondragover = function(e){ e.preventDefault(); };
drop.ondragout = function(e){ e.preventDefault(); };
drop.ondragenter = function(e){ drop.className = 'image-drop hover'; }
drop.ondragleave = function(e){ drop.className = 'image-drop'; }
drop.ondrop = function(e){
drop.className = 'image-drop';
console.log("dropped", e);
var files = e.dataTransfer.files;
if (files && files.length) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e){
var img = new Image;
img.onload = function(){
var target = 20;
var size = Math.max(img.width, img.height);
var c = document.createElement('canvas');
var x = c.getContext('2d');
c.width = c.height = target;
// determine biggest side
var big = (img.width > img.height) ? 'w' : 'h';
var bsize = big=='w'?img.width/target:img.height/target;
var tw = img.width / bsize;
var th = img.height / bsize;
// now put centered on canvas
x.fillStyle = 'white';
x.fillRect(0,0,target,target);
var tx = +(Math.floor((target-tw)/2).toFixed(2));
var ty = +(Math.floor((target-th)/2).toFixed(2));
x.drawImage(img, 0, 0, img.width, img.height, tx, ty, target, target);
// send to server...
var data = c.toDataURL();
data = data.substring(data.indexOf(',')+1);
Ajax.post('upload',{data:data}, function(s){ console.log("response", s); });
};
img.src = reader.result;
};
reader.onabort = function(e){
console.log("FileReader was aborted", e);
};
reader.onerror = function(e){
console.log("FileReader threw an error", e);
};
reader.readAsDataURL(file);
}
};

On the PHP end of things, you can do something like this. Assuming you post the data in a key called data, you need to replace spaces with plusses, due to the inconsistent way php and js do their encoding/decoding.

Code:
$data = str_replace(' ','+',$_POST['data']);
$data = base64_decode($data);
file_put_contents($id.'.png', $data);

Here's some css code to make the dropdown area pulsate when you hover over it:

Code:
@keyframes pulse {
0% { background: white; }
100% { background: #6af; }
}
.active-drop-target {
animation-name: pulse;
animation-duration: 0.7s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: in-and-out;
background: #6af;
}

Don't forget to prefix all the animation and keyframes properties with your favorite browser prefix. All of them! :)