- 第一步:如果只是统一对所有图片进行限制,我们只需要给富文本里面所有的img标签统一给一个样式即可,代码如下:
tinymce.init({
...其他配置,
content_style: 'img {max-width:100px;max-height:200px;vertical-align:top}',
});
- 第二步:第一种方式虽然能够实现对图片的控制,但是相信大家也能看出来,这样做不能自适应于各种图片,会让图片出现变长变宽的效果,这样子肯定是不好的,所以我们需要用到paste粘贴插件来进行拦截修改,代码如下;
import "tinymce/plugins/paste";
tinymce.init({
...其他配置,
content_style: 'img {max-width:100px;max-height:200px;vertical-align:top}',
paste_postprocess: async function (plugin, args) {
console.log("复制粘贴paste_postprocess", args.node);
const nodeList = args.node.childNodes;
let imgFlag = false;
for (let i = 0; i < nodeList.length; i++) {
let el = nodeList[i];
if (el.localName === "img") imgFlag = true;
}
if (nodeList.length === 1 && imgFlag) {
let base64 = {
dataURL: nodeList[0].src,
type: "image/jpeg",
};
const file = base64ToFile(base64, new Date().getTime()),
const data = request({
file
})
const img = document.createElement("img");
img.src = data.url;
img.onload = () => {
const scale = img.naturalHeight / 50;
const width = (img.naturalWidth / scale).toFixed(0);
const height = 50;
const style = `style="width:${width}px;height:${height}px;"`;
tinymce.execCommand(
"mceInsertContent",
false,
`<img src=${data.url} ${style}/><br/>`
);
};
}
}
})
function base64ToFile(dataUrl, name) {
var arr = dataUrl.dataURL.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], name + ".jpg", { type: "image/jpg" });
}