Thumbnail generation with canvas
Original: http://jsfiddle.net/codepo8/YHWgA/
by Jens Grochtdreis
HTML
<section>
<form>
<label for="upload">Pick image</label>
<input type="file" id="upload" name="upload">
<input type="submit" value="make it so!">
</form>
</section>
<output><p>Thumbnails</p></output>
CSS
* {
margin: 0;
padding: 0;
font-size: 15px;
font-family: helvetica, arial, sans-serif;
}
footer, section, header, aside, figure {
display: block;
}
canvas {
border: 1px solid #000;
}
.dragdrop section {
width: 300px;
height: 300px;
background: #ccc;
color: #999;
text-align: center;
line-height: 300px;
float: left;
margin-right: 10px;
}
.dragdrop output {
width: 500px;
display: block;
float: left
}
output img {
padding: 5px;
}
footer {
clear:both;
}
JavaScript
if (typeof FileReader !== 'undefined' ) {
var s = document.querySelector( 'section' ),
o = document.querySelector( 'output' ),
c = document.createElement( 'canvas' ),
cx = c.getContext( '2d' ),
thumbsize = 100;
c.width = thumbsize;
c.height = thumbsize;
document.body.classList.add( 'dragdrop' );
s.innerHTML = 'Drop images here';
s.addEventListener( 'dragover', function ( evt ) {
evt.preventDefault();
}, false );
s.addEventListener( 'drop', function (ev) {
var files = ev.dataTransfer.files;
if ( files.length > 0 ) {
var i = files.length;
while ( i-- ) {
var file = files[ i ];
if ( file.type.indexOf('image') !== -1 ) {
var reader = new FileReader();
reader.readAsDataURL( file );
reader.onload = function ( ev ) {
var img = new Image();
img.src = ev.target.result;
img.onload = function() {
cx.clearRect( 0, 0, thumbsize, thumbsize );
if( this.width > this.height ) {
var h = this.height * thumbsize / this.width;
cx.drawImage(img, 0, ( thumbsize - h ) / 2, thumbsize, h );
}
if( this.width < this.height ) {
var w = this.width * thumbsize / this.height;
cx.drawImage( img, ( thumbsize - w ) / 2, 0, w, thumbsize );
}
if( this.width === this.height ) {
cx.drawImage( img, 0, 0, thumbsize, thumbsize );
}
var thumb = new Image();
thumb.src = c.toDataURL();
o.appendChild( thumb );
}
};
}
}
}
ev.preventDefault();
}, false );
}