Skip to content

Instantly share code, notes, and snippets.

@kotarou3
Last active October 6, 2015 10:27
Show Gist options
  • Save kotarou3/f5b918b01eb808ab1f18 to your computer and use it in GitHub Desktop.
Save kotarou3/f5b918b01eb808ab1f18 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<section>
<input type="file" id="input" />
<input type="number" id="maxWidth" /> &times; <input type="number" id="maxHeight" />
<button onclick="convert()">Convert</button>
</section>
<section><pre id="output"></pre></section>
<section><img id="outputImage"></pre></section>
<script type="application/javascript">
function convert() {
var image = new Image;
image.onload = function () {
var width = image.width;
var height = image.height;
var maxWidth = parseInt(document.getElementById("maxWidth").value, 10) || Infinity;
var maxHeight = parseInt(document.getElementById("maxHeight").value, 10) || Infinity;
var scale = Math.max(1, height / maxHeight, width / maxWidth);
width /= scale;
height /= scale;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(image, 0, 0, width, height);
URL.revokeObjectURL(image.src);
var result = canvas.toDataURL("image/png");
document.getElementById("output").textContent = result;
document.getElementById("outputImage").src = result;
};
image.onerror = alert.bind(window, "Not an image!");
image.src = URL.createObjectURL(document.getElementById("input").files[0]);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment