/**
* 下载图片类
*/
export class DownloadImg {
/**
* 下载图片
* @param url
*/
public static downloadImg(url: string) {
this.convertUrlToBase64(url).then(res => {
// 图片转为base64
const blob = this.convertBase64UrlToBlob(res); // 转为blob对象
// 下载
if (this.myBrowser() == 'IE') {
window.navigator.msSaveBlob(blob, name + '.jpg');
} else if (this.myBrowser() == 'FF') {
window.location.href = url;
} else {
const a = document.createElement('a');
a.download = name;
a.href = URL.createObjectURL(blob);
a.click();
}
});
}
/**
* base64转换
* @param url
* @private
*/
private static async convertUrlToBase64(url: any) {
return new Promise(function(resolve) {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.src = url;
img.onload = function() {
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();
const dataURL = canvas.toDataURL('image/' + ext);
const base64 = {
dataURL: dataURL,
type: 'image/' + ext,
ext: ext,
};
resolve(base64);
};
});
}
/**
* 加工blob对象
* @param base64
* @private
*/
private static convertBase64UrlToBlob(base64: any) {
const parts = base64.dataURL.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; i++) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
/**
* 浏览器判断
*/
public static myBrowser() {
const userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
if (userAgent.indexOf('OPR') > -1) {
return 'Opera';
} //判断是否Opera浏览器 OPR/43.0.2442.991
if (userAgent.indexOf('Firefox') > -1) {
return 'FF';
} //判断是否Firefox浏览器 Firefox/51.0
if (userAgent.indexOf('Trident') > -1) {
return 'IE';
} //判断是否IE浏览器 Trident/7.0; rv:11.0
if (userAgent.indexOf('Edge') > -1) {
return 'Edge';
} //判断是否Edge浏览器 Edge/14.14393
if (userAgent.indexOf('Chrome') > -1) {
return 'Chrome';
} // Chrome/56.0.2924.87
if (userAgent.indexOf('Safari') > -1) {
return 'Safari';
} //判断是否Safari浏览器 AppleWebKit/534.57.2 Version/5.1.7 Safari/534.57.2
}
}