图片上传之前压缩大小并转为base64上传

压缩照片大小

// 文件转为url
function filetoDataURL(file, fn) {
    const reader = new FileReader()
    reader.onloadend = function (e) {
        fn(e.target.result)
    }
    reader.readAsDataURL(file)
}

// url 转为image
function dataURLtoImage(dataurl, fn) {
    const img = new Image()
    img.onload = function () {
        fn(img)
    }
    img.src = dataurl
}

// 通过canvas重置文件大小
function canvasResizetoFile(canvas, quality, fn) {
    canvas.toBlob(function (blob) {
        fn(blob)
    }, 'image/jpeg', quality)
}
// 将图片转为canvas
function imagetoCanvas(image){
    const cvs = document.createElement('canvas')
    const ctx = cvs.getContext('2d')
    cvs.width = image.width
    cvs.height = image.height
    ctx.drawImage(image, 0, 0, cvs.width, cvs.height)
    return cvs
}

// 压缩文件大小
function fileResizetoFile(file, quality, fn) {
    filetoDataURL(file, function (dataurl) {
        dataURLtoImage(dataurl, function (image) {
            canvasResizetoFile(imagetoCanvas(image), quality, fn)
        })
    })
}

// 最终调用压缩方法, 获取到压缩后的文件

fileResizetoFile(this.state.file, 0.5, res => {
    console.log(res) // 返回 blob格式文件
}

将图片转为base64格式字符串

function convertImgToBase64 (url, callback, outputFormat) {
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let img = new Image()
        img.crossOrigin = 'Anonymous'
        img.onload = function(){
            canvas.height = img.height
            canvas.width = img.width
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
            callback(canvas.toDataURL(outputFormat || 'image/png'))
            canvas = null
        }
        img.src = window.URL.createObjectURL(url)
    }

上传调用


fileResizetoFile(this.state.file, 0.5, res => {
    console.log(res) // 返回 blob格式文件
    convertImgToBase64(res, base64Str => {
       // 最终获取到base64
        console.log(base64Str)
        // ajax.post(xxx)
        // ...
    })
}

感谢 JS中图片压缩