How to rescale Image to 12 x 12 Automatically whenever someone select a file from computer <input type=“file” name=“image[]” class=“box_file” />

白昼怎懂夜的黑 提交于 2020-12-15 05:18:06

问题


My Goal is to rescale the image automatically to 12 x 12 whenever someone select the file from desktop. Eg: - If user select 1000 x 500 image i want it to automatically rescale to 12 x 12

HTML:

<input type="file" name="files[]" class="myimage" />

(Using Javascript)


回答1:


If you want the image to have a certain dimensions such as 12x12 as soon as it loads, you will need to add a class to the image by listening to the 'load' event of the image. Like this:

The class will be applied as soon as the image is loaded from desktop, and within this class you will specify your required dimensions.

EDIT: I have updated my post as per your comment. Please make sure to specify these important details in the question itself while asking in the future.

Run the below code snippet and upload any sized image but when it loads here it will have 100px x 100px.

const input = document.querySelector(".myimage");

input.addEventListener("change", function () {
  if (input.files && input.files[0]) {
    const reader = new FileReader();

    reader.addEventListener("load", function (e) {
      document.querySelector("img").src = e.target.result;
      document.querySelector("img").classList.add("rescale-img");
    });
    reader.readAsDataURL(input.files[0]);
  }
});
.rescale-img{
    width: 100px;
    height: 100px;
    }
<input type="file" name="files" class="myimage" /> 
<img src="#">



回答2:


You can just do this:

function activate() {
  document.getElementById("image").style.width = "12rem"
  document.getElementById("image").style.height = "12rem"
}
<img src="https://upload.wikimedia.org/wikipedia/en/9/95/Test_image.jpg" id="image"></img>
<button onclick="activate()">Activate small thingy</button>

Edit the size to your liking, but 12px is too small.



来源:https://stackoverflow.com/questions/64831445/how-to-rescale-image-to-12-x-12-automatically-whenever-someone-select-a-file-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!