Skip to content

Instantly share code, notes, and snippets.

Created August 11, 2017 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/55d1ba60129bb5b13c740b8624caedf5 to your computer and use it in GitHub Desktop.
Save anonymous/55d1ba60129bb5b13c740b8624caedf5 to your computer and use it in GitHub Desktop.
Video and image thumbnail for HTML file upload
<input type="file" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4" />
<p><strong>Select a video or image file</strong><br /><br />Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)</p>
<div></div>
document.getElementsByTagName('input')[0].addEventListener('change', function(event) {
var file = event.target.files[0];
var fileReader = new FileReader();
if (file.type.match('image')) {
fileReader.onload = function() {
var img = document.createElement('img');
img.src = fileReader.result;
document.getElementsByTagName('div')[0].appendChild(img);
};
fileReader.readAsDataURL(file);
} else {
fileReader.onload = function() {
var blob = new Blob([fileReader.result], {type: file.type});
var url = URL.createObjectURL(blob);
var video = document.createElement('video');
var timeupdate = function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
video.pause();
}
};
video.addEventListener('loadeddata', function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
}
});
var snapImage = function() {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var image = canvas.toDataURL();
var success = image.length > 100000;
if (success) {
var img = document.createElement('img');
img.src = image;
document.getElementsByTagName('div')[0].appendChild(img);
URL.revokeObjectURL(url);
}
return success;
};
video.addEventListener('timeupdate', timeupdate);
video.preload = 'metadata';
video.src = url;
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
video.play();
};
fileReader.readAsArrayBuffer(file);
}
});
div {
line-height: 200px;
}
img {
max-width: 200px;
max-height: 200px;
padding: 5px;
vertical-align: middle;
text-align: center;
}
@supports (object-fit: cover) {
img {
width: 200px;
height: 200px;
object-fit: cover;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment