Js图片转base64,base64转file上传服务器

2022-05-05 20:11:29 浏览数 (1)

代码语言:javascript复制
function imgToBase64(url, callback) {
    let canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image
    img.crossOrigin = 'Anonymous'
    img.src = url
    img.onload = () => {
        canvas.height = img.height
        canvas.width = img.width
        ctx.drawImage(img, 0, 0)
        let dataURL = canvas.toDataURL('image/png')
        callback(dataURL)
        canvas = null
    }
}

function base64ToFile(data, callback) {
    let base = window.atob(data.substring(data.indexOf(',')   1))
    let length = base.length
    let url = new Uint8Array(length)
    while (length--) {
        url[length] = base.charCodeAt(length)
    }
    let file = new File([url], `${new Date().getTime()}.jpg`, {
        type: 'image/jpg'
    })
    callback(file)
}

0 人点赞