图片格式转换

图片canvas,file,blob,DataURL等格式转换。

file转base64

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
<title>base</title>
</head>
<body>
<input type="file" name="" id="file">
<img src="" id="img">
<script type="text/javascript">
// 方法一:利用URL.createObjectURL() ==> blob:null/xxxxxx
window.onload = function () {
let $img = document.getElementById('img')
file.onchange = function (e) {
console.log(e.target.files[0])
let file = e.target.files[0]
let fileUrl = window.URL.createObjectURL(file)
$img.src = fileUrl
img.onload = function () {
// 手动回收
URL.revokeObjectURL(fileUrl)
}
}
}

// 利用FileReader.readAsDataURL() ==> data:image/jpeg;base64,xxxxxx
window.onload = function () {
let $img = document.getElementById('img')
file.onchange = function (e) {
console.log(e.target.files[0])
let file = e.target.files[0]
const fr = new FileReader(file)
fr.readAsDataURL(file)
fr.onload = function () {
$img.src = this.result
}
}
}
</script>
</body>
</html>

canvas转DataURL

1
2
3
4
5
6
7
8
// toBlob(callback, type, quality)
// callback
// 回调函数,可获得一个单独的 Blob 对象参数。如果图像未被成功创建,可能会获得 null 值。
// type 可选
// DOMString 类型,指定图片格式,默认格式(未指定或不支持)为 image/png。
// quality 可选
// Number 类型,值在 0 与 1 之间,当请求图片格式为 image/jpeg 或者 image/webp 时用来指定图片展示质量。如果这个参数的值不在指定类型与范围之内,则使用默认值,其余参数将被忽略。
canvas.toBlob(function(blob){...}, "image/jpeg", 0.95); // JPEG at 95%

Blob对象显示图片

1
2
3
4
canvas.toBlob(function (blobObj) {
let imgSrc = window.URL.createObjectURL(blobObj)
document.getElementById('img').src = imgSrc
})

下载DataURL表示的图片

1
2
3
4
5
6
function downloadImg () {
let aLink = document.createElement('a')
aLink.download = 'fileName.png' // 文件名后缀需要和dataurl表示的相同,否则可能乱码
aLink.href = dataUrl
aLink.click()
}
------本文结束 感谢阅读------