@gdjiami/jslib
Version:
Jiami FrontEnd helpers and Services
116 lines (102 loc) • 3.58 kB
JavaScript
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { setupLocalPreviewUrl } from './string';
function canvasDataURL(url, obj) {
return _regeneratorRuntime.async(function canvasDataURL$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", new Promise(function (resolve, reject) {
var img = new Image();
img.src = url;
img.onload = function () {
// 默认按比例压缩
var w = img.width > 4000 ? 4000 : img.width;
var h = img.height > 4000 ? 4000 : img.height;
var scale = w / h;
w = obj.width || w;
h = obj.height || w / scale; // 生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d'); // 创建属性节点
var anw = document.createAttribute('width');
anw.nodeValue = w.toString();
var anh = document.createAttribute('height');
anh.nodeValue = h.toString();
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(img, 0, 0, w, h); // quality值越小,所绘制出的图像越模糊
canvas.toBlob(function (blob) {
if (blob) {
resolve(blob);
}
}, 'image/jpeg', obj.quality);
};
img.onerror = reject;
}));
case 1:
case "end":
return _context.stop();
}
}
});
}
/**
* 对图片进行压缩处理,通过压缩比率控制输出文件的大小
*
* @param file 图片文件
* @param quality 压缩比率
*
*/
export function compressImage(file, quality) {
return _regeneratorRuntime.async(function compressImage$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
return _context3.abrupt("return", new Promise(function _callee(resolve) {
var bl;
return _regeneratorRuntime.async(function _callee$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return _regeneratorRuntime.awrap(canvasDataURL(setupLocalPreviewUrl(file), {
quality: quality
}));
case 2:
bl = _context2.sent;
resolve(new File([bl], file.name, {
type: file.type
}));
case 4:
case "end":
return _context2.stop();
}
}
});
}));
case 1:
case "end":
return _context3.stop();
}
}
});
}
/**
* 对图片进行压缩处理,通过传入的 maxSize, 控制输出文件的大小,压缩到小于 maxSize,或者到达最小压缩比的文件
*
* @param file 图片文件
* @param maxSize 压缩最大值,单位字节
*
*/
export function compressImageBySize(file, maxSize) {
return _regeneratorRuntime.async(function compressImageBySize$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
return _context4.abrupt("return", compressImage(file, Math.min(maxSize / file.size, 1)));
case 1:
case "end":
return _context4.stop();
}
}
});
}