js 图片转换为指定大小的DataUrl

来源:互联网 发布:阳江市网络问政平台 编辑:程序博客网 时间:2024/06/05 17:32
将图片转换为指定大小的DataUrl:
/** * @description 将input-file选中图片文件转换为指定大小base64的DataURL * element input-file元素(必须) * width 图片转换后宽度(可选) * height 图片转换后高度(可选) **/function toDataURL(element, width, height){if (element.files && element.files[0]) {var reader = new FileReader();reader.readAsDataURL(element.files[0]);reader.onload = function(event){var img = new Image();img.src = event.target.result;var c = document.createElement("canvas");// width、height参数缺省时处理if(width == null && height == null){width = img.width;height = img.height;}else if(width == null){var ratio = height / img.height;width = img.width * ratio;}else if(height == null){var ratio = width / img.width;height = img.height * ratio;}c.width = width;c.height = height;var ctx = c.getContext("2d");img.onload = function(){ctx.drawImage(this, 0, 0, width, height);/** 这里进行图片处理后业务逻辑的处理 **///console.log(c.toDataURL(element.files[0].type))$("body").append("<img id='test' src='" + c.toDataURL(element.files[0].type) + "' style='border:1px solid #f00;' widht=" + width +" height=" + height + " />");}}}}

0 0
原创粉丝点击