Summernote富文本编辑器:限制图片超出特定高宽尺寸
Adding Image Dimension Restrictions to Summernote Image Upload
Great job getting the file size restriction working already! Let's extend that code to add checks for image width and height. Here's how you can implement it smoothly:
Step-by-Step Breakdown
- We'll use the native
Imageconstructor to load the uploaded image data, which lets us access its actual width and height once loaded. - Define your maximum allowed width and height (tweak these values to match your specific requirements).
- Layer the dimension check right alongside your existing size validation before inserting the image into the editor.
Modified Code with Combined Size + Dimension Checks
onImageUpload(images, insertImage) { // Define your restriction thresholds here const MAX_FILE_SIZE = 100000; // 100KB const MAX_IMAGE_WIDTH = 1920; // Adjust to your max width const MAX_IMAGE_HEIGHT = 1080; // Adjust to your max height for (let i = 0; i < images.length; i++) { const currentImage = images[i]; // First validate file size if (currentImage.size > MAX_FILE_SIZE) { alert('Image not saved, max allowed image size is 100kb'); continue; // Skip to next image if size fails } const reader = new FileReader(); reader.onloadend = () => { // Create an image element to extract dimensions const tempImg = new Image(); tempImg.src = reader.result; tempImg.onload = () => { // Check if width OR height exceeds the set limits if (tempImg.width > MAX_IMAGE_WIDTH || tempImg.height > MAX_IMAGE_HEIGHT) { alert(`Image not saved, max allowed dimensions are ${MAX_IMAGE_WIDTH}x${MAX_IMAGE_HEIGHT}px`); return; } // All checks passed—insert the image into Summernote insertImage(reader.result); }; }; reader.readAsDataURL(currentImage); } };
Key Details to Note
- I moved the size check inside the loop so each uploaded image is validated individually (handles multi-image uploads gracefully).
- The
tempImg.onloadcallback is critical—we can only reliably get the image's dimensions after it's fully loaded into the temporary image element. - Adjust
MAX_IMAGE_WIDTHandMAX_IMAGE_HEIGHTto whatever threshold makes sense for your use case. - The
continuestatement ensures that if one image fails the size check, the loop still processes the remaining images instead of stopping entirely.
This setup will now block images that are either too large in file size or exceed your specified width/height limits before they're added to the editor.
内容的提问来源于stack exchange,提问作者Sudarshan More
相关产品推荐
相关产品推荐

