如何在AngularJS中按设定最大值自动裁剪图片(支持1:1适配)
AngularJS实现指定尺寸的图片自动裁剪
要实现你需要的图片自动裁剪逻辑,我们可以借助HTML5的Canvas API在前端完成处理,直接修改你现有的fileinputpost指令即可,核心是读取图片后根据尺寸规则进行裁剪,再转成base64格式。
核心逻辑规则
- 当图片任一维度超过1080px:先将图片等比例缩放到最长边为1080px,再从中心裁剪出1080x1080的正方形区域
- 当图片长宽都≤1080px:直接从图片中心裁剪出1:1的正方形区域(以较短边的长度为裁剪尺寸)
修改后的完整指令代码
app.directive("fileinputpost", [function() { return { scope: { fileinputpost: "=", postfile: "=", namepost: "=", typepost: "=" }, link: function(scope, element, attributes) { element.bind("change", function(changeEvent) { scope.fileinputpost = changeEvent.target.files[0]; var files = changeEvent.target.files; var ext = files[0].name.match(/\.(.+)$/)[1]; scope.namepost = Math.random().toString(36).substr(2, 19) + "." + ext; scope.typepost = files[0].type; var reader = new FileReader(); reader.onload = function(loadEvent) { // 创建图片对象获取原始尺寸 const img = new Image(); img.src = loadEvent.target.result; img.onload = function() { let imgWidth = img.width; let imgHeight = img.height; const maxSize = 1080; let targetWidth, targetHeight; let cropX = 0; let cropY = 0; // 处理超尺寸图片的缩放 if (imgWidth > maxSize || imgHeight > maxSize) { const scaleRatio = maxSize / Math.max(imgWidth, imgHeight); targetWidth = Math.floor(imgWidth * scaleRatio); targetHeight = Math.floor(imgHeight * scaleRatio); } else { targetWidth = imgWidth; targetHeight = imgHeight; } // 计算1:1裁剪的中心区域坐标 const cropSize = Math.min(targetWidth, targetHeight); cropX = Math.floor((targetWidth - cropSize) / 2); cropY = Math.floor((targetHeight - cropSize) / 2); // 创建Canvas执行裁剪绘制 const canvas = document.createElement('canvas'); canvas.width = maxSize; canvas.height = maxSize; const ctx = canvas.getContext('2d'); // 完成裁剪+尺寸转换的绘制操作 ctx.drawImage( img, cropX, cropY, cropSize, cropSize, // 原图中要裁剪的区域 0, 0, maxSize, maxSize // 在Canvas上绘制的目标区域 ); // 将处理后的图片转为base64并更新scope scope.$apply(function() { scope.postfile = canvas.toDataURL(scope.typepost).split(',')[1]; }); }; } reader.readAsDataURL(scope.fileinputpost); }); } } }]);
关键代码说明
- 图片尺寸获取:通过创建
Image对象加载读取后的base64图片,获取原始宽高信息 - 缩放逻辑:当图片超出1080px限制时,按最长边等比例缩小,保证图片整体比例不变
- 裁剪区域计算:始终取图片中心的正方形区域,确保裁剪后的图片主体居中
- Canvas绘制:利用
drawImage方法一次性完成裁剪和尺寸转换,最终输出标准的1080x1080图片 - base64转换:将Canvas内容转为对应格式的base64字符串,替换原有直接赋值逻辑,适配你现有的数据传递规则
内容的提问来源于stack exchange,提问作者Bimo
相关产品推荐
相关产品推荐

