1

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.

kfm
  • 143
  • 3
  • 17
  • Possible duplicate of [JavaScript reduce the size and quality of image with based64 encoded code](http://stackoverflow.com/questions/20379027/javascript-reduce-the-size-and-quality-of-image-with-based64-encoded-code) – georgeawg Apr 04 '17 at 16:29
  • I tried it, but I got this error: `Error: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap.` – kfm Apr 04 '17 at 16:46
  • When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. – georgeawg Apr 04 '17 at 16:49

2 Answers2

3
    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();
    }
Sanjeev S
  • 1,113
  • 2
  • 13
  • 33
Rogério Oliveira
  • 414
  • 1
  • 4
  • 15
1

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;
};
B3none
  • 385
  • 3
  • 18