最近遇到了图片压缩的问题,想在前端控制一下,所以有了一下代码。 一.canvas.toDataURL()
具体使用方法为:canvas.toDataURL(type,encoderOptions)
第一个参数type为,支持的类型,默认为images/png,第二个参数是质量,默认为0.92
注意事项:1、图片跨域问题 2、画布高度为0,会返回字符串”data:,” 3、图片类型,如:image/png、image/jpeg、image/webp 4、图片质量如为默认,则小心压缩的图片质量很有可能比原有大,如我上传一张120kb的图片,压缩后很有可能为140kb,base64会增加一部分。 简单示例:
1 2 3 4 var fullQuality = canvas.toDataURL("image/jpeg" , 1.0 );var mediumQuality = canvas.toDataURL("image/jpeg" , 0.5 );var lowQuality = canvas.toDataURL("image/jpeg" , 0.1 );
完整代码:
1 <img src="" alt="" id="img" crossorigin="anonymous">
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 function drawImg (path, callback ) { var img = new Image(); img.src = path; img.onload = function ( ) { var w = this .width, h = this .height; var quality = 0.75 ; var canvas = document .createElement('canvas' ); var ctx = canvas.getContext('2d' ); canvas.setAttribute("width" , w); canvas.setAttribute("height" , h); ctx.drawImage(this , 0 , 0 , w, h); var base64 = canvas.toDataURL('image/jpeg' , quality); console .log("压缩后的质量:" + base64.length / 1024 * quality); callback(base64); }; }; drawImg("xinghaivps.png" , function (base ) { document .getElementById("img" ).src = base; })
二、canvas.drewImage()
完整代码:
1 <canvas id="myCanvas"></canvas>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 function render (src,size ) { var image = new Image(); image.onload = function ( ) { var canvas = document .getElementById("myCanvas" ); if (image.height > size) { image.width *= size / image.height; image.height = size; } var ctx = canvas.getContext("2d" ); ctx.clearRect(0 , 0 , canvas.width, canvas.height); canvas.width = image.width; canvas.height = image.height; ctx.drawImage(image, 0 , 0 , image.width, image.height); }; image.src = src; }; render('mei.jpg' ,1500 )
参考:
打赏
上次更新:2024-10-10 17:42:49