追求长久的幸福,会获得长久的快乐。追求短暂的刺激,会获得短暂的快感与无尽的悔恨
在工作中经常遇到转换图片格式的需求,现在总结下
/**
- @desc url转Base64
- @param url {String} 图片url地址
- @param type {image/jpeg} 图片转换类型
*/
function fnUrlToBase64 (url, type = 'image/jpeg') {
return new Promise((resolve, reject) => {
const img = new Image()
const canvas = document.createElement('canvas');
img.crossOrigin = '*';
img.onload = () => {
const width = img.width, height = img.height;
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// 设置底色为白色
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 在画布上绘制图像
ctx.drawImage(img, 0, 0, width, height);
const base64 = canvas.toDataURL(type);
resolve(base64);
};
img.onerror = () => {
reject(new Error('message'));
};
img.src = url;
});
}
/**
- @desc File、Blob转base64
- @param file {Object} 文件
*/
function fnFileToBase64 (file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', () => {
const base64 = reader.result?.toString() || '';
resolve(base64);
});
reader.addEventListener('error', () => {
reject(new Error('message'));
});
reader.readAsDataURL(file);
});
}
// 调用
<input type="file" id="upload">
document.querySelector('#upload').onchange = (event) => {
fnFileToBase64(event.target.files[0]).then(res=> {
console.log(res)
})
}
/*
* @desc 将File图片对象转为 base64且尺寸不超过 800
* @param file {Object} file图片对象
* */
fnImageSizeCompress(file, nSize = 800) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
const image = new Image();
let sBase64Src = '';
image.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
let width = image.width;
let height = image.height;
// 获得图片宽高比,大于1说明宽比高大,小于1说明高比宽大
let rate = width / height;
if (width > nSize || height > nSize) {
width = rate > 1 ? nSize : nSize * rate;
height = rate < 1 ? nSize : nSize / rate;
}
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
sBase64Src = canvas.toDataURL(file.type);
resolve(sBase64Src);
}
reader.readAsDataURL(file);
reader.onload = (e => {
image.src = e.target.result;
});
image.onerror = () => {
reject();
}
})
}
/**
* @desc url转Blob(fetch)
* */
function fnUrlToBlob(url) {
return window.fetch(url).then(response => response.blob());
}
/**
* @desc url转Blob(XMLHttpRequest)
* */
fnUrlToBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
}
/*
* base64转Blob对象
* data(string)==》base64
* return Blob 对象
* */
function fnDataURItoBlob(data) {
let byteString;
if (data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(data.split(',')[1])
} else {
return;
}
let mimeString = data.split(',')[0].split(':')[1].split(';')[0];
let ia = new Uint8Array(byteString.length)
for (let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i)
}
return new Blob([ia], {type: mimeString})
}
new Blob([this.file], { type: "image/png" })
/*
* @desc 将一个canvas对象转变为一个Blob对象
* @param canvas {canvas} canvas对象
* @param type {String} 图片类型
* @param quality {Number} 图片质量
* */
function fnCanvasToBlob(canvas, type = 'image/png', quality = 1) {
return new Promise(resolve => canvas.toBlob(blob => resolve(blob), type, quality))
}
// blob转url
function fnBlobToUrl(blob) {
return URL.createObjectURL(blob);
}
function fnBase64ToUrl(data) {
var parts = data.split(';base64,'),
contentType = parts[0].split(':')[1],
raw = window.atob(parts[1]),
length = raw.length,
arr = new Uint8Array(length);
for (var i = 0; i < length; i++) {
arr[i] = raw.charCodeAt(i);
}
var blob = new Blob([arr], { type: contentType });
return URL.createObjectURL(blob);
};
document.querySelector('button').onclick = () => {
fnDownloadFile('./p2678027668.jpg', '忍冬')
}
/**
* @desc 下载文件
* @param url {String} 文件链接
* @param filename {String} 文件名称
* */
function fnDownloadFile (url, filename) {
// 下载源数据文件,生成blob对象
window.fetch(url).then(response => response.blob()).then(blob => {
fnDownFile(blob, filename)
})
}
/**
* @desc 下载文件
* @param blob {Blob} Blob文件
* @param filename {String} 文件名称
* */
function fnDownFile (blob, filename) {
const a = document.createElement('a');
a.download = filename;
const blobUrl = URL.createObjectURL(blob);
a.href = blobUrl;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(blobUrl);
}
谢谢你阅读到了最后~
期待你关注、收藏、评论、点赞~