Skip to content
Advertisement

Upload compressed image file from client-side using JavaScript

I am trying to compress images on client side using JavaScript on some low bandwidth devices and I’m currently stuck in a limbo using the HTML5 File API. I’m new to this, please bear with me if I’m missing something important.

I have some input tags which should ideally open the mobile camera, capture single image, compress and send files to the backend. Although this can be done with a single input field with multiple uploads enabled but I need the multiple image fields to segregate images based on some categories.

Here’s the input boxes:

JavaScript

Here’s the image compression logic:

JavaScript

In PHP script, I’d usually try to catch files from the POST request like:

JavaScript

But this doesn’t work because it looks for the original user selected file at a tmp directory (e.g. the actual temporary file in my case is C:xampptmpphp25CB.tmp )

One thing I’ve tried is put the input fields outside of the form tags, enabled the click behaviour using a button and created new input field with the modified data within the form like:

JavaScript

Needless to say, this had no effect and the PHP script could not identify any file.

Please guide me and suggest any changes required in the JavaScript/PHP script so I can accept the modified file and not the original user uploaded file from the input field.

Advertisement

Answer

  1. You can only change a file input value with another list
    here is how: https://stackoverflow.com/a/52079109/1008999 (also in the example)
  2. Using the FileReader is a waste of time, CPU, Encoding & decoding and RAM…
    use URL.createObjectURL instead
  3. Don’t use canvas.toDataURL… use canvas.toBlob instead
  4. Canvas have bad compression, read earlier comment and see the jsfiddle proff
    If you insist on using canvas to try and squeeze the size down then
    1. First try to see if the image is in a reasonable size first
    2. Compare if the pre existing image file.size is smaller than what the canvas.toBlob provides and choose if you want the old or the new one instead.
    3. If resizing the image isn’t enough have a look at this solution that change the quality until a desired file size & image aspect have been meet.

Without any testing, this is how i would have refactor your code too:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement