Compress Images Before Uploading for Performance | JavaScript

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 ต.ค. 2024
  • Don't forget to like and subscribe!
    This is episode 2 in a series on tips for building better user experience for your users with poor connectivity.
    In this episode, learn how to resize your images on the client-side with a canvas element so you can drastically increase the upload times of images to your app. 🚀
    Image compression can really help with the performance of your app before you upload it.
    Tricks like this with JavaScript always help you build faster apps.
    🔗 Starter Code
    github.com/cod...
    🔗 Completed here:
    github.com/cod...
    💜 Subscribe for more videos 💜
    Follow Niall Maher
    💙 / nialljoemaher
    💜 / nialljoemaher
    💙 / nialljoemaher
    💜 dev.to/nialljo...
    Codú is a software development company in Dublin Ireland. To work with us reach out via our website here: www.codu.ie
    #javascript #webdevelopment #code

ความคิดเห็น • 105

  • @Dovvik
    @Dovvik 3 ปีที่แล้ว +3

    This one was helpful. Dispite some misleading things such as :
    - All intermediate usages of DOM HTMLImageElement are not necessary (and actually adding confusion, should have been using new Image() objects for clarity)
    - line 29 of your code is wrong and I don't know why you don't get an error (the first parameter of .toDataURL() call is incorrect, should be directly the target type instead of the Image itself)
    But at the end of the day, the procedure is nicely describing how to resize an image with canvas and I wouldn't have achieved what I wanted without your help. So thank you.

    • @codu
      @codu  3 ปีที่แล้ว +2

      Old habits for me I guess! I will check that out and do an update over the coming months. Been a while since I looked at the code for this so I will take a look 👀

  • @AshtonMotana
    @AshtonMotana ปีที่แล้ว

    Great tutorial, finally found a an example of working code to resize images.

  • @patcodingcodester9781
    @patcodingcodester9781 3 ปีที่แล้ว

    Dude small suggestion, but you should make sure the thumbnail video shows code. Maybe I missed it, but I almost went right passed this video because I wanted to see an actual example. I'm really glad I ended up clicking though. Great content and exactly what I was looking for. Thanks!

  • @GraemeWant
    @GraemeWant 3 ปีที่แล้ว

    Very Good. I have done this before, but never really understood what was happening. Thanks, very informative.

  • @neza05
    @neza05 7 หลายเดือนก่อน

    Let's give it a try.

  • @FredySandoval_123
    @FredySandoval_123 3 ปีที่แล้ว

    Men! I read it and read it, and I just couldn't get it, but your explanation was awesome.

  • @marimuthur9456
    @marimuthur9456 2 ปีที่แล้ว

    Your really awesome it's very easy to understand as well as easy method too thank you so much👌🏼👌🏼👌🏼👌🏼

  • @LibraryOfTheOligarchs
    @LibraryOfTheOligarchs 11 หลายเดือนก่อน

    This was helpful! Appreciate you!

  • @davidkeyemm2332
    @davidkeyemm2332 3 ปีที่แล้ว +2

    Hello Codù Community, thank you so much for this tutorial. It helps me a lot, I'm just starting to learn JS. Can you tell me after compressing the image, how to upload to my server ? Should I use formData ?

  • @kasperkat2004
    @kasperkat2004 2 ปีที่แล้ว +1

    This was an excellent explanation ! Please do one using libwebp / cwebp for a folder of images . I have a grandfather from Northern Ireland .

  • @EddieMao
    @EddieMao 8 หลายเดือนก่อน

    Fantastic tutorial, I like it.

  • @Fedupbrummie
    @Fedupbrummie 6 หลายเดือนก่อน

    Hi , what programming tool are you using , I'm just using gedit a linux text editor but what you are using looks far better , thanks for the tutorial

  • @zamtouch
    @zamtouch 3 ปีที่แล้ว

    awesome stuff bro... really added great value to my project

  • @thatgeezeruk
    @thatgeezeruk 3 ปีที่แล้ว

    This is so gorgeous - can you do this on multiple images?

  • @scottmcmahon7209
    @scottmcmahon7209 3 ปีที่แล้ว +1

    Also, the title of the video says that you are compressing the images, but from what I can tell it looks like you are resizing it. Can you compress and resize images using your method in the video?

  • @urosciric8030
    @urosciric8030 3 ปีที่แล้ว +1

    Thank you so much! I will attempt to make an npm package based on this

    • @shubhsaraswat4096
      @shubhsaraswat4096 3 ปีที่แล้ว

      Any luck?

    • @urosciric8030
      @urosciric8030 3 ปีที่แล้ว +1

      @@shubhsaraswat4096 Yes, it works very well. I'm using it in my masters degree work. I'm building a barebones lightroom so it's taking some time.

  • @jayraj3872
    @jayraj3872 4 ปีที่แล้ว +3

    Thank you...the javascript code works very fine....but can u please tell how to replace the original Image by srcEncoded (compressed image) while uploading.

    • @SAMIULISLAM-qf4dq
      @SAMIULISLAM-qf4dq 2 ปีที่แล้ว

      Iam also facing the same problem... Can anybody please help...

    • @dchubad
      @dchubad 8 หลายเดือนก่อน

      you can't. The fileList is readonly.

  • @zandp7629
    @zandp7629 ปีที่แล้ว

    Thank's brother

  • @AshtonMotana
    @AshtonMotana 6 หลายเดือนก่อน

    I came back to this as I've made a ton of progress, The quality setting doesn't change the quality of the image, so when you convert the base64 string back into a Jpeg blob and then to a new File, the jpeg will not be compressed, only resized. same photo downsized to 720p as uncompressed jpeg is 724KB, but when converting the canvas to a webp, the same outputted image is 85KB
    canvas.toBlob((blob) => {
    const myImage = new File([blob], "myNewImage.webp", { type: blob.type });
    console.log(myImage)
    testFunction(myImage)
    }, 'image/webp || jpeg', 0.5 || Quality) // if you change the 'image/webp' to image/jpeg as well as the name with file extension, this will create as a jpeg and the file size will be larger the webp, but not nearly as large as the uncompressed jpeg, 144kb. This is fantastic now.

  • @PTM1008
    @PTM1008 3 ปีที่แล้ว

    I didn't get the part where you said "you can use multi-step upload if you're using something like AWS"

  • @cahyosu763
    @cahyosu763 2 ปีที่แล้ว

    this what i need, thanks

  • @NERD_T.I
    @NERD_T.I 2 ปีที่แล้ว

    Thank you very much, save my life!

  • @davidofug
    @davidofug 3 ปีที่แล้ว

    This is awesome. Thank you
    How about allowing a user to resize and a crop an image by themselves. Thank you

  • @niyampoudel2520
    @niyampoudel2520 3 ปีที่แล้ว +1

    Hey Man, thanks a lot, one question, How do I get the srcEncoded out from the onload function. Thanks

  • @cyber_Dean
    @cyber_Dean ปีที่แล้ว

    Excellent

  • @botanmh
    @botanmh 3 ปีที่แล้ว +1

    it is great, but how can I convert srcEncoded to a format such as we can get from (document.querySelector("#upload").files[0]). because when I POST to API backend using axios, it will be reject.

  • @fauzi5848
    @fauzi5848 3 ปีที่แล้ว

    excuse me, may I know what font and color scheme do you use sir?, it looks so charming

  • @AshishRawat-zl6te
    @AshishRawat-zl6te 4 ปีที่แล้ว

    Amazing video Man !!!

  • @jguille26
    @jguille26 3 ปีที่แล้ว +1

    hi thanks for the content. I hope you are fine!
    a query.
    How could I send the compressed image to a folder on the server as an image?

  • @MrOlivom
    @MrOlivom 2 ปีที่แล้ว

    Hi man! Thanks for the video! How can I upload the new image into database? Thanks again!!

  • @SAMIULISLAM-qf4dq
    @SAMIULISLAM-qf4dq 2 ปีที่แล้ว +2

    How can i upload this compressed image file on server ??

    •  2 ปีที่แล้ว

      It is also my question. Could you get that to work?
      I saw in same places they use canvas.toBlob and create a new File in its callback function but nothing seems to work for me.

  • @BiharGaurav
    @BiharGaurav 2 ปีที่แล้ว +1

    I see that you have done resizing instead of compressing. Can you share some code for compressing?

    • @Shinerweb
      @Shinerweb 2 ปีที่แล้ว

      I also created demo with code, if you want code then please check out our profile

  • @RohitKumar-xs3wh
    @RohitKumar-xs3wh 4 ปีที่แล้ว

    great tutorial bro! thank you.

    • @codu
      @codu  4 ปีที่แล้ว

      Thanks!

  • @muhammadnurfaqqih4651
    @muhammadnurfaqqih4651 3 ปีที่แล้ว +1

    its a really good video, many thanks man, just need more improvement on your explanation 🔥🔥

  • @cotigasenegal
    @cotigasenegal 3 ปีที่แล้ว +1

    This code is cool, but what about the upload?
    A bit of PHP after the JS to upload to the server would be welcome (for me anyway :)

    • @codu
      @codu  3 ปีที่แล้ว +2

      Time is usually the issue. I think there’s a good few questions from people here so I might do a video soon showing an end to end solution 🍺

    • @szymonpopielarz7701
      @szymonpopielarz7701 3 ปีที่แล้ว +2

      @@codu Did you make any video about this? I wanna create form with resizingimage. It will be very useful.

  • @dchubad
    @dchubad 8 หลายเดือนก่อน

    i tried this but it just uploads the original file size. once files[0] has a file it becomes readonly

  • @ulohhijbuloh8266
    @ulohhijbuloh8266 3 หลายเดือนก่อน

    how to upload the image has been resized to folder?

  • @scottmcmahon7209
    @scottmcmahon7209 3 ปีที่แล้ว

    Towards the end of the video you mentioned that if I was to upload the image to aws S3 I would need a multistep form. Why would I need a multistep form if I am going to upload to aws S3?

  • @issaissifou3579
    @issaissifou3579 3 ปีที่แล้ว

    Thank you so much!

  • @aleksandarhristov5695
    @aleksandarhristov5695 4 ปีที่แล้ว +1

    Much appreciated!!!

    • @codu
      @codu  4 ปีที่แล้ว

      You are welcome!

  • @yousuf4you
    @yousuf4you 3 ปีที่แล้ว

    one of the best video... ❤️️

  • @storybox1234
    @storybox1234 3 ปีที่แล้ว +1

    This code is good, but what about the srcEncoded image upload using php? please replay!

    • @codu
      @codu  3 ปีที่แล้ว

      I decided to keep the video shorter and on the resizing part. There are different ways people handle uploading of images for optimisations and if I went the route I would have ended up talking for another 20 minutes. 😂

  • @bidyutmahanta85
    @bidyutmahanta85 2 ปีที่แล้ว

    Hi, Can you please tell the type of e in the image onload function?

  • @bz6304
    @bz6304 3 ปีที่แล้ว +1

    Love your videos. Towards the end, I got this error in my console.
    app.js:15 Uncaught DOMException: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs.
    at process
    at HTMLButtonElement.onclick

    • @codu
      @codu  3 ปีที่แล้ว

      Let me look into it, I haven’t seen this error or jump into the Discord so you can share your code and I can help 😄

  • @tuanbui3023
    @tuanbui3023 ปีที่แล้ว

    this way doesn't keep original size of image. I want to keep width and height. I use quality option to compress image with same original width and height. But with same original width and height, canvas maybe make size of image larger. So i have to calculate agian to the size i want. Can you suggest some another way to compress image but keep original width and height?
    tks a lot

  • @robertkylethomas173
    @robertkylethomas173 4 ปีที่แล้ว

    Thanks mate, you just earned a subscriber

    • @codu
      @codu  4 ปีที่แล้ว

      Thanks for the sub! Great to have you here 🤘

    • @robertkylethomas173
      @robertkylethomas173 4 ปีที่แล้ว +1

      @@codu quick question the API I'm posting the smaller image to is expecting an image with the type of File - is there an easy way to convert the smaller image to a file?

    • @codu
      @codu  4 ปีที่แล้ว

      I think you can do something like canvas.toDataURL("image/png");
      If that doesn't work fairly straightforwardly let me know! There is always a way 😁

    • @robertkylethomas173
      @robertkylethomas173 4 ปีที่แล้ว

      So this is how I got it to work eventually - after following the steps in the tutorial:
      const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpg");
      fetch(srcEncoded)
      .then((res) => res.blob())
      .then((res: Blob) => {
      this.shrunkenImage = this.convertBlobToFile(res, file.name);
      });
      Then the convertBlobToFile:
      public convertBlobToFile = (theBlob: Blob, fileName: string): File => {
      return new File([theBlob], fileName, {
      lastModified: new Date().getTime(),
      type: theBlob.type,
      });
      };
      There probably are nicer ways of doing it but that worked for me

  • @tarakaramsurala1305
    @tarakaramsurala1305 3 ปีที่แล้ว

    "Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported." Can you please help me on this issue

  • @usama_khalid
    @usama_khalid 3 ปีที่แล้ว

    great video ... thanks....

  • @mylearningclub6179
    @mylearningclub6179 2 ปีที่แล้ว

    thank u

  • @mcifci
    @mcifci 3 ปีที่แล้ว

    thank you

  • @AnkushMhaskar-p3v
    @AnkushMhaskar-p3v ปีที่แล้ว

    i upload the png file so this compressed or not

  • @nurullosulaimonov5663
    @nurullosulaimonov5663 4 ปีที่แล้ว +1

    I have tried but srcEcnoded is "data:," . why it is happening?

    • @codu
      @codu  4 ปีที่แล้ว

      The line `const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");` converts the canvas to a image data URL (which you can use directly as an image or or to save the image as a string if needed), it just gives a simple way of working with the image file.
      developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
      developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

    • @medley5670
      @medley5670 3 ปีที่แล้ว

      @nurullo sulaimonov see this! stackoverflow.com/questions/30079423/canvas-todataurl-returns-data

  • @danielsousa5611
    @danielsousa5611 3 ปีที่แล้ว

    Is it possible create a new input name="image_thumb" filled with the resized image for submit as, and with, original image?

  • @othellovancalbert1541
    @othellovancalbert1541 3 ปีที่แล้ว

    Hi, I' am really excited that I ran into your TH-cam. I just subscribed. However, I keep receiving "Uncaught TypeError: Cannot set property 'src' of null" >app.js:11:19; 14:44; index.html:11:37 via vscode debug console and from same error via Chrome's inspect > "at FileReader.reader.onload" (app.js:14) document.querySelector("#input").src = event.target.result;
    I even update the app.js from Github.
    I am connected, able to upload an image, but no response when clicking the process button. Am I missing something?

  • @ariebervoets419
    @ariebervoets419 2 ปีที่แล้ว

    Great tutorial. But resized image looses EXIF and IPTC data.

    • @codu
      @codu  2 ปีที่แล้ว

      That’s a good thing to note! I totally forgot about that as a side effect

  • @p21qq18
    @p21qq18 3 ปีที่แล้ว

    why my output is not showing , help me please

  • @guldenizeryilmaz6548
    @guldenizeryilmaz6548 3 ปีที่แล้ว

    wery thanks. wish you shown we to how to put srcEncoded instead of file[0] .
    ( HttpPostedFileBase file
    WebImage img = new WebImage(file.InputStream);
    if (img.Width > 1000)
    { img.Resize(1000, 1000); })
    Because I send original file[0] server and resize image on server, I saw image with for example 1000x1000 and size:101 kb but I send srcEncoded and convert srcEncoded to image file, I saw image width 400x400 but image size 517kb.
    note: original file size : 2610kb

  • @psychedelarte7257
    @psychedelarte7257 4 ปีที่แล้ว

    Merci

  • @developerhabits
    @developerhabits 4 ปีที่แล้ว

    Nice video!

    • @codu
      @codu  4 ปีที่แล้ว +1

      Glad you enjoyed it, keep up the awesome work yourself 💜

  • @yudelko
    @yudelko 3 ปีที่แล้ว +2

    You are just resizing the image ...not really compressing it ...that to implement an algorithm for example like jpeg

  • @divyamishra9615
    @divyamishra9615 3 ปีที่แล้ว

    Can we check the size of the resized image that we are getting in canvas?? Like i had a 4mb image after resizing how to check the size of that same image?

    • @codu
      @codu  3 ปีที่แล้ว +1

      I haven’t actually tried that, I’ll do an experiment with it 🤔

    • @divyamishra9615
      @divyamishra9615 3 ปีที่แล้ว

      @@codu if you try and succeed, please post about it.. i am stuck with something similar like if i want to check whether the resized image is smaller than a particular size (ex: 1Mb), there is no property to check that.

  • @erturkyorulmaz7376
    @erturkyorulmaz7376 3 ปีที่แล้ว

    Sir, Although ı choose a .jpg file, when ı want to save new image as, it is a .png? What shoul I do?

  • @شرطةمكافحةالحكاكين
    @شرطةمكافحةالحكاكين 3 ปีที่แล้ว

    ولا ولا خد قلبي يلا take my heart

    • @codu
      @codu  3 ปีที่แล้ว

      Thank you!

  • @esrefatak
    @esrefatak 2 ปีที่แล้ว +3

    Sorry, but this is not compress, it is a resize exactly

  • @turtrueweb
    @turtrueweb 3 ปีที่แล้ว

    +

  • @thechoosen4240
    @thechoosen4240 ปีที่แล้ว

    Good job bro, JESUS IS COMING BACK VERY SOON;WATCH AND PREPARE