kfm
kfm

Reputation: 143

set size of a base64 image javascript - angularjs

I saw many answers but I didn't find a good solution for this:

I have a picture in my $scope.file = /9j/4VeIRXhpZgAASUkqAAgAAAAL [..] And it size is 5217984 = 5 MB

But this picture is só big and my angular aplication/web service is not supporting it.

What have I to do? And how?

I'm trying to convert this 5 MB image to a image with 500 KB but I didn't get it. Can anyone help my please?

I don't know if it its possible, but I need a function in javascript to convert that 5MB image to a image with 500 KB for example, and I can riseze it.

And its everything right in my application when I put a image with 500 KB fir example.

Upvotes: 1

Views: 4042

Answers (2)

Rogério Oliveira
Rogério Oliveira

Reputation: 514

    var $scope.getData= function () {

        var reader = new FileReader();
        reader.onload = $('input[type=file]')[0].files;
        var img = new Image();
        img.src =(reader.onload[0].result);
            img.onload = function() {
                if(this.width > 640)
                {
                    //Get resized image
                    img= imageToDataUri(this, 640, 480);
                }
            }   
    };

    //Resize the image (in the example 640 x 480px)
    function imageToDataUri(img, width, height) {

        // create an off-screen canvas
        const canvas = document.createElement('canvas'),
        const ctx = canvas.getContext('2d');

        // set its dimension to target size
        canvas.width = width;
        canvas.height = height;

        // draw source image into the off-screen canvas:
        ctx.drawImage(img, 0, 0, width, height);

        // encode image to data-uri with base64 version of compressed image
        return canvas.toDataURL();
    }

Upvotes: 3

B3none
B3none

Reputation: 409

If you have access to the encoded base64 just use this function:

$scope.getFileSize = function (base64encoded) {
    try {
        var encodedString = base64encoded.split(',')[1]
    } catch (errorMsg) {
        return false;
    }

    var decodedBase64 = atob(encodedString);

    return decodedBase64.length;
};

Upvotes: 1

Related Questions