You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CKEditor5:复制大图片时需先调整尺寸再转Base64

无需依赖第三方库调整CKEditor5复制图片的尺寸

可以直接利用原生浏览器API(Canvas + FileReader)重写Base64UploadAdapter的图片处理逻辑,实现自定义尺寸压缩,完全不需要额外依赖库。具体步骤如下:

1. 自定义Base64UploadAdapter

替换CKEditor默认的Base64UploadAdapter,在适配器内部插入图片压缩逻辑:

class CustomBase64UploadAdapter {
    constructor( loader ) {
        this.loader = loader;
    }

    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                // 调用自定义压缩函数
                compressImage(file, { maxWidth: 1200, maxHeight: 1200, quality: 0.8 })
                    .then( compressedBlob => {
                        const reader = new FileReader();
                        reader.onload = () => {
                            resolve({ default: reader.result });
                        };
                        reader.onerror = reject;
                        reader.readAsDataURL(compressedBlob);
                    })
                    .catch( reject );
            } ) );
    }

    abort() {
        // 可选:添加中止逻辑
    }
}

2. 实现原生图片压缩函数

用Canvas实现图片缩放与质量压缩,保持原图比例:

function compressImage(file, options = {}) {
    const { maxWidth = 1000, maxHeight = 1000, quality = 0.9 } = options;
    return new Promise( (resolve, reject) => {
        const img = new Image();
        img.src = URL.createObjectURL(file);
        img.onerror = reject;

        img.onload = () => {
            URL.revokeObjectURL(img.src);
            
            // 计算缩放后的尺寸,保持比例
            let width = img.width;
            let height = img.height;
            if (width > maxWidth) {
                height = (height * maxWidth) / width;
                width = maxWidth;
            }
            if (height > maxHeight) {
                width = (width * maxHeight) / height;
                height = maxHeight;
            }

            // 创建Canvas绘制压缩后的图片
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);

            // 转换为Blob(支持更多格式,比toDataURL更高效)
            canvas.toBlob(
                blob => {
                    if (!blob) {
                        reject(new Error('图片压缩失败'));
                        return;
                    }
                    // 保留原文件名和类型
                    const compressedFile = new File([blob], file.name, { type: file.type });
                    resolve(compressedFile);
                },
                file.type,
                quality
            );
        };
    });
}

3. 注册自定义适配器到CKEditor5

在CKEditor初始化配置中替换默认的Base64UploadAdapter:

ClassicEditor
    .create( document.querySelector( '#editor' ), {
        extraPlugins: [ editor => {
            editor.plugins.get('FileRepository').createUploadAdapter = loader => {
                return new CustomBase64UploadAdapter( loader );
            };
        } ]
    } )
    .catch( error => {
        console.error( error );
    } );

补充说明

  • 如果需要处理图片EXIF旋转问题(比如手机拍摄的图片方向异常),可以通过读取图片的EXIF信息调整Canvas的绘制角度,这部分也可以用原生API实现,不需要额外库
  • 可以根据需求调整maxWidth、maxHeight和quality参数,平衡图片尺寸和清晰度
  • canvas.toBlob比toDataURL更节省内存,处理大图片时更稳定

内容的提问来源于stack exchange,提问作者Prabhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:55:07