@artmate/chat
Version:
借鉴字节开源react库AntX,通过vue实现的版本
34 lines (33 loc) • 1.28 kB
JavaScript
const R = (t) => t.indexOf("image/") === 0;
function g(t) {
return new Promise((r) => {
if (!t || !t.type || !R(t.type)) {
r("");
return;
}
const n = new Image();
if (n.addEventListener("load", () => {
const { width: e, height: E } = n, a = e / E, o = a > 1 ? 200 : 200 * a, i = a > 1 ? 200 / a : 200, s = document.createElement("canvas");
s.width = o, s.height = i, s.style.cssText = `position: fixed; left: 0; top: 0; width: ${o}px; height: ${i}px; z-index: 9999; display: none;`, document.body.append(s);
const d = s.getContext("2d");
d == null || d.drawImage(n, 0, 0, o, i);
const c = s.toDataURL();
s.remove(), window.URL.revokeObjectURL(n.src), r(c);
}), n.crossOrigin = "anonymous", t.type.startsWith("image/svg+xml")) {
const e = new FileReader();
e.addEventListener("load", () => {
e.result && typeof e.result == "string" && (n.src = e.result);
}), e.readAsDataURL(t);
} else if (t.type.startsWith("image/gif")) {
const e = new FileReader();
e.addEventListener("load", () => {
e.result && r(e.result);
}), e.readAsDataURL(t);
} else
n.src = window.URL.createObjectURL(t);
});
}
export {
R as isImageFileType,
g as previewImage
};