简体   繁体   English

如何改进 .png 到 .jpeg 的转换

[英]how to improve .png to .jpeg conversion

I am using the below code to convert .png data URL to less size .jpeg data URL.我正在使用以下代码将 .png 数据 URL 转换为较小的 .jpeg 数据 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?这里每个 .png 数据 URL 大小为 40mb 或以上,所以我下面的代码花费了太多时间来创建较小的 jpeg。有没有办法让它更快?

    <!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如何提高这个函数的代码性能,.png转.jpeg时间太长

HTML5 Canvas is not preferred here due to its inefficiency with larger files. HTML5 Canvas 在这里不是首选,因为它处理较大的文件效率低下。 You can use sharp library to achieve same with Javascript(Node.js backend).您可以使用sharp库来实现与Javascript(Node.js后端)相同的功能。

sharp
- High performance Node.js image processing - 高性能 Node.js 图像处理
- Fastest module to resize JPEG, PNG, WebP and TIFF images - 调整 JPEG、PNG、WebP 和 TIFF 图像大小的最快模块
- Uses the libvips library - 使用 libvips 库

Read Docs https://sharp.readthedocs.io/en/v0.17.0/install/阅读文档https://sharp.readthedocs.io/en/v0.17.0/install/

Pros and Cons of HTML5 Canvas HTML5 Canvas 的优缺点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM