前端代码进行图像压缩
2018-03-07 19:00
681 查看
<html>
<head>
</head>
<!--前端代码进行图像压缩-->
<body>
<input id="file" type="file">
</body>
</html>
<head>
</head>
<!--前端代码进行图像压缩-->
<body>
<input id="file" type="file">
</body>
<!-- //基本思想 将图片尺寸等比压缩到最大高度,然后画到画布上,将画布转为图片 --> <script> var maxHeight = 1024; var maxWidth = 1024; //获取到上传文件的元素 var el = document.getElementById("file"); el.addEventListener('change', function(event) { var file = event.target.files[0]; var size = file.size; console.log('origin size:', size) minPicture(file, maxHeight, maxWidth) .then( (fileBlob) => { //获取到blob就可以做想做的事情了,比如转为URL console.log(fileBlob); }) }) function minPicture(file, maxHeight, maxWidth) { var canvas = document.createElement("canvas"); var reader = new FileReader(); var img = new Image(); var ctx = canvas.getContext('2d'); return new Promise((resolve, reject) => { img.addEventListener('error', reject); img.addEventListener('load', function () { var height = img.height; var width = img.width; //计算一个合适的压缩比例, //如果高度超过规定的,通过高度进行等比压缩 //如果宽度超过规定的,通过宽度压缩 //如果高度、宽度都超过,则使用需要压缩比例大的数字作为压缩比例 let rate = 1; if (maxWidth && width > maxWidth) { rate = width / maxWidth; } if (maxHeight && height > maxHeight) { let rate2 = height / maxHeight; if (rate2 > rate) { rate = rate2; } } //更新压缩后的高度宽度 height = height / rate; width = width / rate; img.height = height; img.width = width; canvas.height = height; canvas.width = width; //清楚画布内容 cxt.clearRect(0, 0, width, height); //绘制图像到画布 cxt.drawImage(img, 0, 0, width, height); //图像转为Blob,也可以转为url canvas.toBlob(resolve); }); reader.addEventListener('error', reject); reader.addEventListener('load', function () { img.src = reader.result; }); reader.readAsDataURL(file); }) } </script>
</html>
相关文章推荐
- python使用pil进行图像处理(等比例压缩、裁剪)实例代码
- 最近邻方法进行图像旋转 c++代码 旋转后图像内容无损失
- javascript 调用rar.exe进行文件压缩代码
- MSDN:C#(.NET)自带的图像压缩代码
- Grunt 5分钟上手:合并+压缩前端代码
- angular配合gulp进行代码打包和压缩
- [前端优化]使用Microsoft Ajax Minifier对资源文件进行压缩优化
- iOS开发有用代码(有判断邮箱格式是否正确的代码、图片压缩、亲测可用的图片上传代码和实现点击图片进行跳转的代码等。)
- 前端见微知著番外篇:Bitbucket进行代码管控
- WP HTML Compression – 轻松压缩前端页面代码
- 微信小程序中上传图片并进行压缩的实现代码
- java 对多文件进行压缩与解压缩代码
- Android ImageUtils 图片工具类,包括:小米从相册调图像空指针,三星旋转照片,压缩图片,保存Bitmap到本地,获取本地视频的缩略图,毛化玻璃效果,代码以后会更新
- Android中进行图像压缩和缩放
- spice 图像压缩算法相关代码逻辑流程
- iOS对图像进行尺寸压缩
- 利用最大熵进行阈值分割从而实现灰度图像的二值化的原理概要及OpenCV代码
- grunt 入门 应用grunt对代码进行压缩
- 编写可测试的前端代码第二部分 – 从反模式进行重构
- iOS开发-进阶:图像进行压缩方法汇总