Skip to content

Instantly share code, notes, and snippets.

@webolizzer
Last active December 12, 2023 09:02
Show Gist options
  • Save webolizzer/329f3713886f51750d587abc65374ea9 to your computer and use it in GitHub Desktop.
Save webolizzer/329f3713886f51750d587abc65374ea9 to your computer and use it in GitHub Desktop.
Create thumbnail from img or video file via file input client-side
<!DOCTYPE html>
<html>
<body>
<script>
// source https://stackoverflow.com/questions/23640869/create-thumbnail-from-video-file-via-file-input
document.addEventListener("DOMContentLoaded", function() {
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);
}
});
});
</script>
<style>
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;
}
}
</style>
<input type="file" accept=".jpg,.jpeg.,.gif,.png,.mov,.mp4,.webm" />
<p><strong>Select a video or image file</strong></p>
<p>Supported browsers (tested): Chrome, Firefox, Safari, Opera, IE10, IE11, Android (Chrome), iOS Safari (10+)</p>
<div></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment