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.

3
  • Possible duplicate of JavaScript reduce the size and quality of image with based64 encoded code Commented Apr 4, 2017 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. Commented Apr 4, 2017 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. Commented Apr 4, 2017 at 16:49

2 Answers 2

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.