0

Boa tarde queridos programadores benfeitores. Estou com um problema, como descrevi no título, que está afetando meus uploads de imagens. A imagem aumenta até 10 vezes o tamanho. E não estou falando em dimensão.

Ex: Inicialmente, tenho uma imagem qualquer, vamos assumir uma extensão .jpg. Essa é a apenas uma imagem qualquer.

Em seguida, faço o upload dessa imagem através do meu sistema, e a salvo no mesmo diretório com um nome diferente, só para podermos compara-las. No entanto, o tamanho dela aumenta de uma forma inaceitável.

Imagem qualquer pós-upload

Estou utilizando JS com o plugin Crop.js para poder ajustar a imagem da maneira que eu quero no front-end, depois, envio para uma Servlet Java para persistir isso num arquivo local.

Entendendo o fluxo

Primeiramente, eu seleciono a imagem do meu computador normalmente:

var input = $("#inputImage"); //The the input field
input.on("change", setCanvas); //bind the "change" event to be fired everytime user set a file from its computer
function setCanvas(e) {
    var reader = new FileReader(); //FileReader to read the input file set by the user
    /**
     * 
     * @param {type} event containing the data read from the file input by the yser
     * @returns {undefined} nothing
     * 
     * This function is called then the FileReader read all the data from the file set by the user.
     */
    reader.onload = function (event) {
        var img = new Image(); //Variable to storage the image set by the input field
        /**
         * 
         * @returns {undefined} nothing
         * 
         * This function is called then the image set by the user is finally loaded by the image source.
         */
        img.onload = function () {
            //When the image finally load...
            canvas.width = img.width; //Set the canvas width to the same of the image set by the user
            canvas.height = img.height; //Set the canvas height to the same of the image set by the user.
            ctx.drawImage(img, 0, 0); //draw the image into canvas using its context.
            $(".modal").modal(); //call the modal with the image
        }

        img.src = event.target.result; //Set the image source with the image set by the user via input field
    }
}

Após isso, depois que o modal é chamado, o plugin Cropper.js é inicializado para poder lidar com edições de crop.

$(".modal").on("shown.bs.modal", function () {
    //This function will be executed when the modal is shown completely.

    //Let's instantiate a cropper to edit the image
    cropper = new Cropper(canvas, {
        dragMode: "move", //allow to move the back-image
        autoCropArea: 0.5, //initiate with the crop in 50% of the image
        cropBoxMovable: true, //The crop box is movable
        cropBoxResizable: true //the crop box is resizable
    });

    $("#upload").on("click", onClick); //bind a click event to the "save" button

}

Depois de tudo editado pelo canvas, esta na hora de pegar as informações do canvas para ser enviado para a Servlet.

function canvasToBlob(canvas, type) {

    var byteString = atob(canvas.toDataURL().split(",")[1]),
            ab = new ArrayBuffer(byteString.length),
            ia = new Uint8Array(ab),
            i;
    for (i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ab], {
        type: type
    });

}

function onClick() {

    var blob = canvasToBlob(cropper.getCroppedCanvas(), filetype); //Get the blob from the canvas

    var fd = new FormData(); //Variable to storage the data that will be send to the server via AJAX

    fd.append("tImage", blob); //append the blob
    fd.append("tImageName", filename); //append the filename

    //Build the ajax request
    $.ajax("url", {
        data: fd,
        type: "POST",
        processData: false,
        contentType: false
    }).done(function (data) {
     //do something...
}

Até aqui tudo bem, vamos checar agora o SERVER-SIDE

    Part part = null; //declares a Part object
    String name = null; //declares a String object

    try {
        part = request.getPart("tImage"); //Get the image coming from user ajax request
        name = request.getParameter("tImageName"); //get the name of the file set by user
    } catch (IOException | ServletException e) {
        //Somethign extremely wrong occured
    }
    //Declares a new "folder" to be created if it doesn't exist.
    File folder = new File(".." + File.separator + "images" + File.separator + "adm" + File.separator);

    if (!folder.exists()) {
        //Checks if folder doesn't exist

        folder.mkdirs(); //Create a new folder
    }

    //Create new File object. As this time, this file represents the image that will be persisted.
    File image = new File(".." + File.separator
            + "images" + File.separator
            + "adm" + File.separator
            + h.getName());
    try {
        image.createNewFile(); //it always creates a new file
        h.getImage().write(image.getCanonicalPath()); //Write the image into disk using Part.write
       }catch (IOException e) {
       //do something here
     }

Bom, é isso. Se alguém tem alguma sugestão, mas não é nada certeza, por favor, não hesite em comentar essa pergunta.

Estou a muito tempo tentando resolver isso e não consegui de jeito nenhum.

5
  • Posso estar enganado, mas parece que você está subindo um bitmap, não um jpg. A falta de compressão explica o tamanho do arquivo.
    – bfavaretto
    30/06/2016 às 21:04
  • Isso porque o que você lê do canvas é o valor da cor de cada pixel.
    – bfavaretto
    30/06/2016 às 21:07
  • Interessante! No caso se eu fizer uma compressão do arquivo, não será mais possível gravar o conteúdo com o Part.write(). Teria que usar outras formais como OutputStream, por exemplo, correto? 30/06/2016 às 21:09
  • Aí já não sei, Java não é comigo...
    – bfavaretto
    30/06/2016 às 21:12
  • Não que isso seja um problema, é que utilizar o Part.write() é mais cômodo. 30/06/2016 às 21:15

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .