Code
var defaultOptions = {
compressType: 'scale',
scale: 1,
imageSize: 0,
imageType: '',
quality: .8,
toBlob: false
}
var options = JSON.parse(JSON.stringify(defaultOptions))
function minify() {
var val = getEl('#file')[0].files[0]
if (val) {
console.log(val, options)
ImgAbout.imgCompress(val, options).then(function (result) {
if (typeof result === 'string') {
getEl('#show-img')[0].src = result
getEl('#show-img')[0].alt = val.name
} else {
console.log(result)
alert('See result in console')
}
}).catch(function (e) {
alert(e.toString())
})
} else {
alert('Please input the image file')
}
}
function bindOptions() {
var fileInput = getEl('#file')[0]
fileInput.addEventListener('change', function (ev) {
const file = ev.target.files[0]
getEl('#imageType')[0].value = file ? file.type : ''
options.imageType = file ? file.type : ''
Base64_Blob.blobToBase64(file).then(url => {
getEl('#origin-img')[0].src = url
getEl('#origin-img')[0].alt = file.name
})
})
var idArr = [
{ id: 'compressType', type: 'select' },
{ id: 'scale', type: 'number' },
{ id: 'imageSize', type: 'number' },
{ id: 'imageType', type: 'text' },
{ id: 'quality', type: 'number' },
{ id: 'toBlob', type: 'checkbox' }
]
idArr.forEach(function (item) {
var id = item.id
var el = getEl('#' + id)[0]
if (el) {
el.value = options[id]
el.checked = options[id]
var f = function (ev) {
if (item.type === 'number') {
options[id] = +ev.target.value
} else if (item.type === 'checkbox') {
options[id] = ev.target.checked
} else {
options[id] = ev.target.value
}
}
el.addEventListener('change', f)
} else {
console.warn('Id `' + id + '` is not exist')
}
})
}
bindOptions()
function download() {
var url = getEl('#show-img')[0].src
var name = getEl('#show-img')[0].alt
if (url) {
var a = document.createElement('a')
a.href = url
a.download = name
a.click()
a.remove()
} else {
alert('Have no compressed image!')
}
}