简体   繁体   English

使用 JavaScript 限制图像比例

[英]Limit image proportions with JavaScript

<input type="file" id="file" accept="image/gif, image/jpeg, image/png">

The HTML code is structured as follows. HTML代码结构如下。 In this case, if an image with a ratio of 1:1 is not entered in the input, I want to move to another page through JavaScript.在这种情况下,如果输入中没有输入比例为1:1的图像,我想通过JavaScript移动到另一个页面。

You basically need to add a handler for the input, and check if the height/width === 1 , you can use this function to validate it:您基本上需要为输入添加一个处理程序,并检查height/width === 1 ,您可以使用这个 function 来验证它:

 const fileUpload = document.getElementById("file"); function validateImage(target) { const reader = new FileReader(); reader.readAsDataURL(fileUpload.files[0]); reader.onload = function (e) { const image = new Image(); image.src = e.target.result; image.onload = function () { const height = this.height; const width = this.width; if (height / width.== 1) { console:log("ASPECT RATIO NOT 1;1"). window.location;href = "#otherpage"; // redirect return false; } // do nothing return true; }; }; }
 <input type="file" id="file" accept="image/gif, image/jpeg, image/png" onchange="validateImage(this)">

Note that this is a very simple validation, normally you would want to add error handlers (eg invalid file, broken image, etc.).请注意,这是一个非常简单的验证,通常您会想要添加错误处理程序(例如无效文件、损坏的图像等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM