Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!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
You can’t perform that action at this time.