一. Image对象转换base64字符串
function imageToBase64Str(img) {
if (!(img instanceof Image)) {
throw new Error('请传入Image对象!');
}
img.setAttribute("crossOrigin", 'Anonymous');
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
const ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
return canvas.toDataURL("image/" + ext);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
二. base64字符串转换Blob对象
function base64StrToBlob(base64Str) {
if (!imageUtils.isBase64Str(base64Str)) {
return;
}
const arr = base64Str.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
三. Blob对象转换为base64字符串
function asyncBlobTobase64Str(blob) {
if (!(blob instanceof Blob)) {
throw new Error('请传入Blob对象!');
}
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise((resolve, reject) => {
try {
reader.addEventListener("load", (event) => {
resolve(event);
});
} catch (error) {
reject(error);
}
});
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
四. 判断是否为base64字符串
function isBase64Str(validateStr) {
let base64Str = "";
try {
base64Str = validateStr?.split(',')[1];
} catch {
return false;
}
const pattern = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/;
return pattern.test(base64Str);
}
五. 图片下载
async function imageDownload({image, imageName}) {
if (!(image instanceof Image)) {
throw new Error('请传入Image对象!');
}
let tempSrc = "";
if (imageUtils.isBase64Str(image.src)) {
tempSrc = image.src;
} else {
const response = await fetch(image.src)
const imgBlob = await response.blob();
tempSrc = window.URL.createObjectURL(imgBlob);
}
const elink = $('', {
download: imageName,
style: "display:none",
href: tempSrc,
}).get(0);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
window.URL.revokeObjectURL(tempSrc);
}
- 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
- 41
- 42
- 43
- 44
六. 图片处理聚合对象
const imageUtils = {
imageToBase64Str,
base64StrToBlob,
asyncBlobTobase64Str,
isBase64Str,
imageDownload
}
export default imageUtils;
七. 使用
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片上传转换title>
head>
<body>
<div>
<input id="imageFile" type="file" accept="image/png, image/jpg, image/jpeg, image/gif" />
<a id="aLink" target="_blank">
<img id="image">
a>
<hr style="margin-bottom: 100px;">
<img id="cdnImage" src="https://img-blog.csdnimg.cn/1ac4e7e97c4347d59955453b1a230a50.png" alt="">
div>
body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js">script>
<script type="module">
import imageUtils from './js/20-图片转换工具类.js';
setTimeout(() => {
const imageInfo = {
image: $("#cdnImage").get(0),
imageName: '下载类测试'
}
imageUtils.imageDownload(imageInfo);
}, 1000);
$("#imageFile").change(async ({currentTarget: {files}}) => {
const file = files[0];
if (!file) {
return;
}
const {
target: {
result: base64Str
}
} = await imageUtils.asyncBlobTobase64Str(file);
$("#image").attr("src", base64Str);
$("#aLink").attr("href", window.URL.createObjectURL(file));
setTimeout(() => {
const imageInfo = {
image: $("#image").get(0),
imageName: "测试文件"
}
imageUtils.imageDownload(imageInfo);
}, 2000);
});
script>
html>

- 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
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76