路上的杨柳依然神彩奕奕的低垂着黄绿色的发丝,好像冬天的降温没带给她们多少伤害。我倒感受到她们内心的寒冷,叶子摸着十分冰冷,也缺少了昔日的水分。冬天的到来,摧残了多少无辜的生命,又演绎了多少生命的童话。
本文实例为大家分享了js实现纯前端压缩图片的具体代码,供大家参考,具体内容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>压缩图片</title> </head> <body> <input id='file' type="file"> <script> var eleFile = document.querySelector('#file') var file; var render = new FileReader(), img = new Image(); render.onload = function(e) { img.src = e.target.result } // 获取图片文件 eleFile.addEventListener('change', function(e) { file = e.target.files[0]; if(file.type.indexOf('image') === 0) { //读取文件,并返回一个URL格式的Base64字符串 render.readAsDataURL(file) } }) //使用canvas把图片画出来 var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); img.onload = function() { //原始尺寸 var originWidth = this.width; var originHeight = this.height; //最大尺寸限制 var maxWidth = 200, maxHeight = 200 // 目标尺寸 var targetWidth = originWidth, targetHeight = originHeight; //当原始尺寸大于200*200时候 if(originWidth > maxWidth || originHeight > maxHeight) { if(originWidth / originHeight > maxWidth / maxHeight) { //更宽 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)) }else { targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)) } } //画图 canvas.width = targetWidth; canvas.height = targetHeight; //清除画布 context.clearRect(0,0,targetWidth, targetHeight) //图片压缩 context.drawImage(img, 0, 0, targetWidth, targetHeight); //canvas 转为blob并上传 canvas.toBlob(function(blob) { try { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() {{ if(xhr.status == 200) { } }} //开始上传 xhr.open('POST','upload.php', true); xhr.send(blob) } catch (error) { console.log(error) } }, file.type || 'image/png') //在页面预览原图片 var div1 = document.createElement('div') div1.innerText = '原图:' document.body.appendChild(div1) document.body.appendChild(img) //canvas预览 var div2 = document.createElement('div') div2.innerText = 'canvas图:' document.body.appendChild(div2) document.body.appendChild(canvas) } </script> </body> </html>
分析:原理是用canvas的生成的图片,控制其大小来进行图片的压缩,需要注意的是,如果图片的尺寸太小,会导致图片模糊,使用时候,注意设置其比例控制。
1、通过FileReader读取图片文件,用 Image来装图片url(可以用来预览) 2、转化成base64字符串模式 3、通过maxWidth,MaxHeight和比例来控制最终的canvas的宽高 4、用canvas画图 5、在把canvas输出blob文件,进行上传
到此这篇关于js实现纯前端压缩图片就介绍到这了。我不敢休息,因为我没有存款;我不敢说累,因为我没有成就;我不敢偷懒,因为我还要生活;我能放弃,但是我不能选择放弃。所以坚强、拼搏是我唯一的选择。更多相关js实现纯前端压缩图片内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!