Upload images increasing the file size by almost 10x

Asked

Viewed 178 times

0

Good afternoon dear programmers benefactors. I have a problem, as I described in the title, that is affecting my image uploads. The image increases up to 10 times the size. And I’m not talking about dimension.

Ex: Initially, I have some image, let’s assume an extension .jpg. Essa é a apenas uma imagem qualquer.

Then I upload this image through my system, and save it in the same directory with a different name, just so we can compare it. However, its size increases in an unacceptable way.

Imagem qualquer pós-upload

I’m using JS with the Crop.js plugin to adjust the image the way I want on the front end, then send it to a Java Servlet to persist it in a local file.

Understanding the flow

First, I select the image of my computer normally:

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
    }
}

After that, after the modal is called, the Cropper.js plugin is initialized to handle Crop edits.

$(".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

}

After everything edited by canvas, it’s time to take the canvas information to be sent to 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...
}

So far so good, let’s check now the 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
     }

Well, this is it. If anyone has any suggestions but is not at all sure, please do not hesitate to comment on this question.

I’ve been trying to figure this out for a long time and I couldn’t do it at all.

  • I might be wrong, but it looks like you’re uploading a bitmap, not a jpg. The lack of compression explains the file size.

  • That’s because what you read from the canvas is the color value of each pixel.

  • Interesting! In case I compress the file, it will no longer be possible to save the content with the Part.write(). You would have to use other forms like Outputstream, for example, correct?

  • Then I don’t know, Java’s not my thing...

  • Not that that’s a problem, is that using the Part.write() is more comfortable.

No answers

Browser other questions tagged

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