let bgcImage = 'http://192.168.0.83:9080/files/4a9c3056-9b9b-4b41-b8e2-fd9f27023c41.jpg' let image = new Image() image.crossOrigin = '' // 必須有這個 image.src = bgcImage image.onload = () => { // 圖片加載完成後,調用getBase64Image方法 let base64ImageSrc = getBase64Image(image) console.log(base64ImageSrc ) } // url轉base64 export function getBase64Image(image, width, height) { // width、height調用時傳入具體像素值,控制大小 ,不傳則默認圖像大小 let canvas = document.createElement('canvas') canvas.width = width !== undefined ? width : image.width canvas.height = height !== undefined ? height : image.height let ctx = canvas.getContext('2d') ctx.drawImage(image, 0, 0, canvas.width, canvas.height) let ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase() let dataURL = canvas.toDataURL('image/' + ext) return dataURL }
// base64轉file export function dataURLtoFile (dataurl, filename) { let arr = dataurl.split(',') let mime = arr[0].match(/:(.*?);/)[1] let bstr = atob(arr[1]) let n = bstr.length let u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } return new File([u8arr], filename, { type: mime }) }