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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.