简体   繁体   中英

How to optimize canvas image and get jpg instead of png

<img id='imgt' src='01.jpg' alt='img'>

var img = document.getElementById("imgt");
    c1 = document.createElement("canvas");
    var ctx = c1.getContext("2d");

    var a = $('#imgt').width();
    var b = $('#imgt').height();

    c1.width = a;
    c1.height = b;
    ctx.drawImage(img, 0, 0, a, b);

So resulting image is the same dimensions as source img, but it has over 1MB while the source image is less than 1MB.

Also the source image is jpg and resulting image is png .

How can I get jpg instead of png and how to optimize resulting image for web?

When you' re making the data URI you can specify

canvas.toDataURL("image/jpeg", 0.95); 

or

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

which will generate a JPG. Just make sure your picture is opaque, because otherwise the background will become black.

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.

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