我正在使用以下代码将.png数据URL转换为较小的.jpeg数据URL。这里每个.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>
如何提高此函数的代码性能,将.png转换为.jpeg需要太多时间
HTML5 Canvas在这里不是首选,因为它对大文件的效率不高。您可以使用[sharp