diff --git a/src/components/FileLoader.vue b/src/components/FileLoader.vue index 3df2ab5..e0fa405 100644 --- a/src/components/FileLoader.vue +++ b/src/components/FileLoader.vue @@ -31,19 +31,12 @@ createPreview(dropFile.value) } - const container = computed(()=>{ - if (fileType.value == 'image') return 'img' - if (fileType.value == 'video') return 'video' - return 'div' - }) - const createPreview = async (file) => { loading.value = true // get file type fileType.value = file.type.toLowerCase().substr(0, file.type.indexOf("/")) - let filePath = (window.URL || window.webkitURL).createObjectURL(file) // store the initial file @@ -52,52 +45,66 @@ // if file is video create a snapshot and use that instead of the orignal file if (fileType.value == 'video') { fileToRead = await videoSnapshot(filePath) - filePath = (window.URL || window.webkitURL).createObjectURL(fileToRead) } + if (fileType.value == 'image') { + fileToRead = await imageSnapshot(filePath) + } + + filePath = (window.URL || window.webkitURL).createObjectURL(fileToRead) + emit('file', fileToRead) const reader = new FileReader() reader.readAsDataURL(fileToRead) reader.onloadend = (e) => { if (e.target.readyState == FileReader.DONE) { - imageSnapshot(filePath) + thumb.value.src = filePath + emit('upload', filePath) + loading.value = false; } } } // TODO: scale image to thumb size const imageSnapshot = (url) => { - thumb.value.src = url - emit('upload', url) - loading.value = false; + return new Promise((resolve, reject)=>{ + let image = document.createElement('img') + image.src = url + image.onload = () => { + let file = snapshot(image) + resolve(file) + } + }) } + + const videoSnapshot = (url) => { - // wrap logic into a promise, in order to wait for the 'canplay' event return new Promise((resolve, reject)=>{ let video = document.createElement('video') video.src = url - - const snapshot = async () => { - let canvas = document.createElement('canvas') - canvas.width = 640 - canvas.height = 360 - let ctx = canvas.getContext('2d') - - ctx.drawImage(video, 0, 0, canvas.width, canvas.height) - thumb.value.src = canvas.toDataURL('image/jpeg') - loading.value = false - video.removeEventListener('canplay', snapshot) - let file = await base64ToBlob(thumb.value.src, 'snapshot') - resolve(file) - } - - video.addEventListener('canplay', snapshot) + video.addEventListener('canplay', ()=>{ + let file = snapshot(video) + video.removeEventListener('canplay', snapshot) + resolve(file) + }) }) } + const snapshot = async (source) => { + let canvas = document.createElement('canvas') + console.log(source) + let width = source.tagName =='IMG' ? source.naturalWidth : source.videoWidth + let height = source.tagName == 'IMG' ? source.naturalHeight : source.videoHeight + canvas.width = 640 + canvas.height = 360 + let ctx = canvas.getContext('2d') + ctx.drawImage(source, 0, 0, canvas.width, canvas.height) + let file = await base64ToBlob(canvas.toDataURL('image/jpeg'), 'snapshot') + return file + }