image大图缩小转成canvas后锯齿的问题
2016-05-18 15:24
225 查看
最近在项目中做到头像本地处理的时候发现一个问题,就是上传的头像源图如果比较大,会导致生成后的头像锯齿比较明显。
为了解决这个问题,网上搜了好多资料,很多都是说不断的缩小图片然后再放大图片,再渲染到canvas,这个方案试过了,但是无论从效率还是效果上都不太尽人意。
后来不小心在github上发现了一个小插件,还真好用,完美的把问题解决了。
这里要感谢一下插件作者,再帮他宣传一下。
插件地址:https://github.com/sapics/scale.js
头像上传处理思路是这样的:
1)<input type'File">接收图片上传
2)把源图片裁剪成目标宽高比例(这里不缩放,一缩放就会有锯齿了)
3)用scale.js插件把裁剪后的图像缩小到目标头像大小
4)canvas.toDataURL()获取目标图像urlBase64,完成
附上代码片断
为了解决这个问题,网上搜了好多资料,很多都是说不断的缩小图片然后再放大图片,再渲染到canvas,这个方案试过了,但是无论从效率还是效果上都不太尽人意。
后来不小心在github上发现了一个小插件,还真好用,完美的把问题解决了。
这里要感谢一下插件作者,再帮他宣传一下。
插件地址:https://github.com/sapics/scale.js
头像上传处理思路是这样的:
1)<input type'File">接收图片上传
2)把源图片裁剪成目标宽高比例(这里不缩放,一缩放就会有锯齿了)
3)用scale.js插件把裁剪后的图像缩小到目标头像大小
4)canvas.toDataURL()获取目标图像urlBase64,完成
附上代码片断
var imgLogo = new Image(); imgLogo.src = _this._config.logo; imgLogo.onload = function() { _this._ctx.drawImage(imgLogo, 0, 0, _this._config.logoWidth, _this._config.signHeight); var imgAvatar = new Image(); imgAvatar.src = _this._config.avatar; imgAvatar.onload = function() { var sx = 0, sy = 0, sw = this.width, sh = this.height, dx = _this._config.logoWidth, dy = 0, dw = _this._config.avatarWidth, dh = _this._config.signHeight; var deltaD = dw / dh, deltaS = sw / sh; if(deltaD > deltaS) { // 高图 var oldSh = sh; sh = (dh / dw) * sw; // 取中间 if(oldSh > sh) { sy = (oldSh - sh) / 2; } } else if(deltaD < deltaS) { // 横图 var oldSw = sw; sw = (dw / dh) * sh; // 取中间 if(oldSw > sw) { sx = (oldSw - sw) / 2; } } // _this._ctx.globalCompositeOperation = 'source-atop'; // 先裁剪 var tCanvas = document.createElement('canvas'), tContext = tCanvas.getContext('2d'); tCanvas.width = Math.floor(sw); tCanvas.height = Math.floor(sh); tContext.drawImage(imgAvatar, Math.floor(sx), Math.floor(sy), Math.floor(sw), Math.floor(sh), 0, 0, Math.floor(sw), Math.floor(sh)); // 再缩小 // 对要计算的值,先取整后再绘图,可以提高效率 var scaleImage = scale({width: Math.floor(dw), height: Math.floor(dh)}, tCanvas, 'jpeg'); _this._ctx.drawImage(scaleImage, Math.floor(dx), Math.floor(dy), Math.floor(dw), Math.floor(dh)); if(typeof callback === 'function') { callback(_this._canvas.toDataURL()); } }; };
相关文章推荐
- 写个IOS应用程序,项目结构可以是这样......
- mysql命令大全
- 【Swift学习】Swift编程之旅---扩展(二十四)
- tp框架总体学习总结(一)
- .net CallBack::Invoke”类型的已垃圾回收委托进行了回调。这可能会导致应用程序崩
- CLR Via C# 第一章(CLR的执行模型)——读书笔记
- Qt Creator 小例子 网上看到的
- virtualbox 网卡设置 主机 虚拟机互 ping 问题
- POJ 1597 find the nth digit (找规律)
- tomcat同时存在多个项目webapp.root问题
- 如何让matlab用mex与C连接使用有例子
- mysql 1449 : The user specified as a definer ('root'@'%') does not exist 解决方法
- word search puzzle
- BZOJ4590 [Shoi2015]自动刷题机
- Java CopyOnWriteArrayList工作原理及实现(一)
- H2 Console Sorry, remote connections ('webAllowOthers') are disabled on this server.的问题解决
- perl 为什么要用引用来做对象呢?
- 关于git基本原理
- 实现复数类中的运算符重载
- Vue.js-----轻量高效的MVVM框架(一、初识Vue.js)