Skip to content Skip to sidebar Skip to footer

How To Rescale Image To 12 X 12 Automatically Whenever Someone Select A File From Computer

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

Solution 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="#">

Solution 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.


Post a Comment for "How To Rescale Image To 12 X 12 Automatically Whenever Someone Select A File From Computer "