Created
September 24, 2018 19:10
-
-
Save pmturner/f40ac17eac04d99924f176f6f8bc9b3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> | |
</head> | |
<body> | |
<form name="uploadForm"> | |
<table> | |
<tbody> | |
<tr> | |
<td>Select Image - <input id="uploadImage" type="file" /></td> | |
</tr> | |
<tr> | |
<td>Original Img - <img id="originalImage"/></td> | |
</tr> | |
<tr> | |
<td>Compress Img - <img id="uploadPreview"/></td> | |
</tr> | |
</tbody> | |
</table> | |
</form> | |
<script type="text/javascript"> | |
$(function() { | |
var fileReader = new FileReader(); | |
var filterType = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i; | |
fileReader.onload = function (event) { | |
var image = new Image(); | |
image.onload=function(){ | |
document.getElementById("originalImage").src = image.src; | |
var canvas = document.createElement("canvas"); | |
var context = canvas.getContext("2d"); | |
var aspect = calculateAspectRatioFit(image.width, image.height, 1024, 768); | |
canvas.width = aspect.width; | |
canvas.height = aspect.height; | |
context.drawImage( | |
image | |
, 0 | |
, 0 | |
, image.width | |
, image.height | |
, 0 | |
, 0 | |
, canvas.width | |
, canvas.height | |
); | |
document.getElementById("uploadPreview").src = canvas.toDataURL('image/jpeg', 0.7); | |
} | |
image.src = event.target.result; | |
}; | |
function calculateAspectRatioFit (srcWidth, srcHeight, maxWidth, maxHeight) { | |
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); | |
return { width: srcWidth*ratio, height: srcHeight*ratio }; | |
} | |
function loadImageFile () { | |
var uploadImage = document.getElementById("uploadImage"); | |
//check and retuns the length of uploaded file. | |
if (uploadImage.files.length === 0) { | |
return; | |
} | |
//validate a valid file. | |
var uploadFile = document.getElementById("uploadImage").files[0]; | |
if (!filterType.test(uploadFile.type)) { | |
alert("Please select a valid image."); | |
return; | |
} | |
fileReader.readAsDataURL(uploadFile); | |
} | |
$('#uploadImage').on('change', function() { | |
loadImageFile(); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment