0

I am using the below code to convert .png data URL to less size .jpeg data URL. here each .png data URL size is 40mb or above so my below code taking too much time to create a less sizejpeg.is there any way to make it faster?

    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="UTF-8">
        <title>Title of the document</title>
    </head>

    <body>
        <button type="button" onclick="compress()">Try it</button>


        <script>
            function compress() {
                maxWidth = 10000;
                var source_img_obj = new Image;


source_img_obj.src = "base64pngimage dataurl"
                var mime_type = "image/jpeg",
                    output_format = "jpeg";

                maxWidth = maxWidth || 10000;
                var natW = source_img_obj.naturalWidth;
                var natH = source_img_obj.naturalHeight;
                var ratio = natH / natW;
                if (natW > maxWidth) {
                    natW = maxWidth;
                    natH = ratio * maxWidth;
                }
                var cvs = document.createElement('canvas');
                cvs.width = natW;
                cvs.height = natH;
                var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
                var newImageData = cvs.toDataURL(mime_type, 0.4);
                var result_image_obj = new Image();
                result_image_obj.src = newImageData;
                console.log(newImageData);
            }
        </script>
    </body>

    </html>

how to improve code performance of this function, it takes too much time to convert .png to .jpeg

KNP
  • 65
  • 1
  • 7
  • 3
    Converting 40MB PNG files in the browser via JavaScript seems an odd choice of tech. – Phil Nov 28 '19 at 04:56

1 Answers1

0

HTML5 Canvas is not preferred here due to its inefficiency with larger files. You can use sharp library to achieve same with Javascript(Node.js backend).

sharp
- High performance Node.js image processing
- Fastest module to resize JPEG, PNG, WebP and TIFF images
- Uses the libvips library

Read Docs https://sharp.readthedocs.io/en/v0.17.0/install/

Pros and Cons of HTML5 Canvas