0

I have an image with a size of around 12MB and it takes time to get loaded. Is there any way to reduce the size of the image to make it load faster? Thanks

New Update: I want to reduce the image size as it gets loaded from an input type file.

Amr yasser
  • 408
  • 5
  • 10
  • 2
    If you dont mind the manual step, you can just use this: https://tiny-img.com/ – MauriceNino Jul 04 '22 at 08:54
  • You're going to need to compress the image. Use something like [imagemagick](https://imagemagick.org/index.php) – Andrew Bone Jul 04 '22 at 08:54
  • 2
    Cannot resize what you have not loaded, so unless you're planning to resize on the backend, the answer is no. – Robby Cornelissen Jul 04 '22 at 08:55
  • 1
    Or use something like [sharp](https://sharp.pixelplumbing.com/) to do it programmatically. – MauriceNino Jul 04 '22 at 08:55
  • you want to do this in javascript in the browser? – Bravo Jul 04 '22 at 09:08
  • @Bravo yes, i want to do that on the browser. I have an image which get loads from an input type file. It takes too long because of its size. – Amr yasser Jul 04 '22 at 09:15
  • 1
    Is there a way to upload only every 16th pixel only from a file? That would function as resizing. – Tamás Sengel Jul 04 '22 at 09:17
  • @MauriceNino I won't be able to use `tiny-img.com` because the images get loaded from an input type file. also for `sharp` because this issue will be implemented in an old technology application that uses only `JavaScript`. – Amr yasser Jul 04 '22 at 09:28
  • 1
    Well, your frontend JavaScript will not be able to resize the image to reduce load. If you do not run NodeJS in your backend, then the question should probably be asked with another tag. – MauriceNino Jul 04 '22 at 09:32
  • And if you want to resize the image *on upload*, you should specify that in the question. – MauriceNino Jul 04 '22 at 09:32
  • 1
    Great. Here is a native JS solution: https://stackoverflow.com/a/24015367/9150652. And here is a module that can do it for you: https://www.npmjs.com/package/pica (although there are probably many others that do a similar thing). – MauriceNino Jul 04 '22 at 09:48

1 Answers1

0

I would suggest you to load images using Image() js method so the remaning content of the page load properly, and use loading = 'lazy' property on the images to make the browser load them only when they are visible in the viewport or when you scroll near to them.

function loadImg(){
var img = new Image(400, 400);
img.src = 'https://pbs.twimg.com/profile_images/1220067947798024192/30eZhfxx_400x400.png';
img.setAttribute("loading", "lazy")
document.body.appendChild(img);
}
#btn{
position: fixed;
top: 5px
}
<input type="button" onclick="loadImg()" value="Load image" id="btn">
hugomztl
  • 88
  • 11