<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="file" onchange="handleChange(this)">
<script>
class ImageToBase64 {
constructor() {
this.imgReg = /^(?:image\/bmp|image\/cis-cod|image\/gif|image\/ief|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x-cmu-raster|image\/x-cmx|image\/x-icon|image\/x-portable-anymap|image\/x-portable-bitmap|image\/x-portable-graymap|image\/x-portable-pixmap|image\/x-rgb|image\/x-xbitmap|image\/x-xpixmap|image\/x-xwindowdump)$/i;
}
_getBase64(imgBlob) {
return new Promise(resolve => {
const fileReader = new FileReader()
fileReader.onloadend = event => {
resolve(event.target.result)
}
fileReader.readAsDataURL(imgBlob)
})
}
getResult(file) {
return new Promise(async (resolve, reject) => {
if (typeof file === "string") { // 如果是图片地址
// 判断是否是图片(正则百度的,可自由替换)
const xhr = new XMLHttpRequest()
xhr.open("GET", file)
xhr.responseType = "blob"
xhr.onload = async () => {
if (xhr.status === 200) { // 状态码正常
const imgBlob = xhr.response
if (this.imgReg.test(imgBlob.type)) { // 是图片类型
const result = await this._getBase64(imgBlob)
resolve(result)
} else {
reject({
code: -1,
msg: "type Error"
})
}
} else {
reject({
code: xhr.status,
msg: xhr.statusText
})
}
}
xhr.send()
} else if (file instanceof Blob || file instanceof File) { // 如果是blob对象
const result = await this._getBase64(file)
resolve(result)
} else {
throw new TypeError("expect a string or File instance object or Blob instance object," +
" but got others")
}
})
}
}
function appendImage(url) {
const oImg = new Image(100, 100)
oImg.src = url
document.body.appendChild(oImg)
}
const imageToBase64 = new ImageToBase64()
// url转base64 测试
!(async () => {
const resultUrl = await imageToBase64.getResult("./images/1.jpg")
appendImage(resultUrl)
})()
// Blob实例对象转base64 测试
async function handleChange(e) {
const [file] = e.files
const resultUrl = await imageToBase64.getResult(file)
appendImage(resultUrl)
}
</script>
</body>
</html>
前端,Blob/File实例对象或普通url转base64图片
最新推荐文章于 2024-04-11 14:42:08 发布