Skip to content

Instantly share code, notes, and snippets.

@BCoulange
Created May 14, 2020 09:56
Show Gist options
  • Save BCoulange/f4bfb4d8aa985687028e522f06e56957 to your computer and use it in GitHub Desktop.
Save BCoulange/f4bfb4d8aa985687028e522f06e56957 to your computer and use it in GitHub Desktop.
<input name="imagefile[]" type="file" id="takePictureField" accept="image/*" onchange="uploadPhotos()" />
<form id="uploadImageForm" enctype="multipart/form-data">
<input id="name" value="#{name}" />
</form>
<img src="" id="preview"/>
<script>
window.uploadPhotos = function(){
// Read in file
var file = event.target.files[0];
// Ensure it's an image
if(file.type.match(/image.*/)) {
console.log('An image has been loaded');
// Load the image
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
// Resize the image
var canvas = document.createElement('canvas'),
max_size = 100,// TODO : pull max size from a site config
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
document.getElementById('preview').src = dataUrl;
document.getElementById('previewCode').text =dataUrl;
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment