JS or Jquery Decrease image size and not just resize

Asked

Viewed 5,032 times

3

Is there any way to decrease the size of the photo before uploading?
Note: It’s not just resize, because some test I did just resize and did not decrease the photo size.
I would like to check if the upload is image type and Decrease in size, for example: from 5mb to 1 or 2Mb, even if for this the image resizes.

Jquery of the Upload:

$(document).ready(function () {

    var files;

    // Add events
    $('input[name=fileUploader]').on('change', prepareUpload);

    // Grab the files and set them to our variable
    function prepareUpload(event) {
        files = event.target.files;
        console.log("aqui",files);
    }

    $('#Salvar').click(function () {
        if (validaDados()) {

             var erro = "";

            var formID = document.getElementById("formulario");

            // files = this.files; // SELECIONA OS ARQUIVOS
            var qtde = files.length; // CONTA QUANTOS TEM
            var tamanho = 0;

            if (qtde > 5) { // VERIFICA SE É MAIOR DO QUE 5
                alert("Não é permitido enviar mais do que 5 arquivos.");
                return false;
            } else {
                for (i = 0; i < qtde; i++) {
                    tamanho += files[i].size;
                }

                if (tamanho > 10000000) {
                    alert("Arquivo acima de uma mega;")
                    return false;
                } else {
                    // SE NÃO FOR MAIS DO QUE 5 ELE CONTINUA.
                    if ($("#destinatario").val() == "") {
                        $("#destinatario").css({ "border-color": "red", "padding": "1px" });
                        $("#errodestinatario").html("E-mail obrigatório!");
                        return false;
                    } else {

                        if (validaEmail($("#destinatario").val())) {
                            $("#destinatario").css({ "border-color": "blue", "padding": "1px" });
                            $("#errodestinatario").html("");
                            $("#formulario").submit();
                        } else {
                            $("#destinatario").css({ "border-color": "red", "padding": "1px" });
                            $("#errodestinatario").html("E-mail Inválido!");
                            return false;
                        }

                    }

                }

            }
        }

    });
    });

HTML:

 <form class="form-horizontal" id="formulario" name="formulario" action="~/Gerenciamento/EnvioEmail/EnviaEmail" method="post" enctype="multipart/form-data">

        <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Destinatario</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="destinatario" name="destinatario" />
                <span class="label label-danger" id="errodestinatario"></span>
            </div>
        </div>
        <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Assunto:</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="assunto" name="assunto" />
                <span class="label label-danger" id="erroassunto"></span>
            </div>
        </div>
        <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Mensagem</label>
            <div class="col-sm-10">
                <textarea class="form-control" id="mensagem" name="mensagem"></textarea>
                <span class="label label-danger" id="erromensagem"></span>
            </div>
        </div>
        <div class="form-group">
            <label for="inputEmail3" class="col-sm-2 control-label">Anexo</label>
            <div class="col-sm-10">
                <input class="form-control" id="fileUploader" name="fileUploader" type="file" multiple />
                <span class="label label-danger" id="erroarquivo"></span>
            </div>
        </div>
        <div id="resposta" style="display:none;"></div>
        <button type="button" class="btn btn-primary" id="Salvar">Enviar</button>




    </form>

1 answer

5


You can use the library compress.js. It uses the canvas API for client-side image compression.

const compress = new Compress()
const preview = document.getElementById('preview')
const output = document.getElementById('output')

const upload = document.getElementById('upload')

upload.addEventListener('change', (evt) => {
  const files = [...evt.target.files]
  compress.compress(files, {
    size: 4, // the max size in MB, defaults to 2MB
    quality: 0.75, // the quality of the image, max is 1,
    maxWidth: 1920, // the max width of the output image, defaults to 1920px
    maxHeight: 1920, // the max height of the output image, defaults to 1920px
    resize: true // defaults to true, set false if you do not want to resize the image width and height
  }).then((images) => {

    const img = images[0]
    // returns an array of compressed images
    preview.src = `${img.prefix}${img.data}`


    const {
      endSizeInMb,
      initialSizeInMb,
      iterations,
      sizeReducedInPercent,
      elapsedTimeInSeconds,
      alt
    } = img

    output.innerHTML = `<b>Start Size:</b> ${initialSizeInMb} MB <br/><b>End Size:</b> ${endSizeInMb} MB <br/><b>Compression Cycles:</b> ${iterations} <br/><b>Size Reduced:</b> ${sizeReducedInPercent} % <br/><b>File Name:</b> ${alt}`
  })
}, false)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://compressjs.herokuapp.com/compress.js"></script>


<div>
  <input type="file" name="" id="upload" accept="image/*">
</div>
<div>
  <br/>
  <img src="" alt="" id="preview">

</div>
<br/>
<p id="output"></p>

  • 1

    I implemented without complication in an application already in production, thank you!

  • Upload implements to be with Base64?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.