Skip to content

Instantly share code, notes, and snippets.

@kevin-shu
Created May 6, 2013 03:20
Show Gist options
  • Save kevin-shu/5523194 to your computer and use it in GitHub Desktop.
Save kevin-shu/5523194 to your computer and use it in GitHub Desktop.
Client-side resizing example
<html>
<head>
<title>Client-side resizing example</title>
</head>
<body>
<input id="file-uploader" type="file"/>
<!-- <p>Image to use:</p>
<img id="cat" src="./cat.jpg" alt="The Scream" > -->
<!-- <p>Canvas:</p>
<canvas id="myCanvas" width="560" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas> -->
<img id="thumbnail" src="" />
<script type="text/javascript">
var LIMIT_LENGTH = 200;
var uploader = document.getElementById("file-uploader");
uploader.onchange = function(e) {
console.log(e);
if(typeof FileReader == "undefined"){
// alert("Oh~oh~");
return true;
}
// var elem = $(this);
var files = e.target.files;
for (var i=0, file; file=files[i]; i++) {
console.log(file);
if (file.type.match('image.*')) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var img = new Image(),
dataUrl = e.target.result,
thumbnail=document.getElementById("thumbnail");
img.src = dataUrl;
img.onload = function () {
var img_width = img.width,
img_height = img.height,
max = Math.max(img_width,img_height),
canvas_width=0,
canvas_height=0,
canvas=document.createElement("canvas"),
ctx = canvas.getContext("2d");
if (img_width==max) {
canvas_width = LIMIT_LENGTH;
canvas_height = LIMIT_LENGTH*img_height/img_width;
} else {
canvas_height = LIMIT_LENGTH;
canvas_width = LIMIT_LENGTH*img_width/img_height;
}
canvas.width = canvas_width;
canvas.height = canvas_height;
ctx.drawImage(img,0,0,canvas_width,canvas_height);
thumbnail.src = (canvas.toDataURL("image/jpg"));
};
}
})(file);
reader.readAsDataURL(file);
}
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment