javaScript:压缩图片并上传
html代码:
<input id="file" type="file" name="filesName">
js代码:
var fileElement = document.getElementById('file');
fileElement.onchange = function(){
var file = event.target.files[0];
var upload = new uploadThumbnail({
// name:"imgFileName", //缺省为 'imgs'
// formName:"formName", //缺省为 'forms'
// max:[maxWidth,maxHeight], //缺省为 [400*400]
file:file,
url:"./thumbnail.php",
dataType:"json", //缺省为 'text'
success:function( data ){
console.info( data ); //打印接收的数据
//this.newImgObj 为压缩后的图片对象
document.body.append( this.newImgObj ) // 将图片加入页面
}
});
upload.explain(); //在控制台打印说明
}
uploadThumbnail 对象:
(function(win,undefined){
'use strict'
var uploadThumbnail = function( obj ){
this.newImgObj = null;
this.init( obj );
this.success = obj.success || function () {};
}
uploadThumbnail.prototype = {
constructor:uploadThumbnail,
// 入口函数
init:function( obj ){
this.compressPictures( obj );
},
// 压缩图片 并将画布传入上传函数
compressPictures:function( obj ){
obj = obj || {};
obj.file = obj.file || "undefined";
obj.url = obj.url || "undefined";
var objThis = this;
if( obj.file == "undefined" || obj.url == "undefined" ){
console.info( "uploadThumbnail: 'file' and 'url' are required" );
return false
};
// 压缩图片需要的一些元素和对象
var reader = new FileReader(), newImg = new Image();
// 缩放图片需要的canvas
var canvas = document.createElement( 'canvas' );
var context = canvas.getContext( '2d' );
if ( obj.file.type.indexOf( "image" )==0 ) {
reader.readAsDataURL( obj.file );
// 文件base64化,以便获知图片原始尺寸
reader.onload = function( e ) {
newImg.src = e.target.result;
// base64地址图片加载完毕后
newImg.onload = function () {
// 图片原始尺寸
var originWidth = this.width;
var originHeight = this.height;
// 最大尺寸限制
var maxWidth, maxHeight;
try{
maxWidth = obj.max[0];
maxHeight = obj.max[1];
}catch( err ){
maxWidth = 400;
maxHeight = 400;
}
// 目标尺寸
var targetWidth = originWidth, targetHeight = originHeight;
// 图片尺寸超过400x400的限制
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对图片进行缩放
canvas.width = targetWidth;
canvas.height = targetHeight;
// 清除画布
context.clearRect( 0,0,targetWidth,targetHeight );
// 图片压缩
context.drawImage( newImg,0,0,targetWidth,targetHeight);
// 完成画布传入上传
objThis.upFile( obj,canvas );
};
};
}else{
return false;
}
},
upFile:function( obj,canvas ){
var objThis = this;
// canvas转为blob并上传
canvas.toBlob(
function (blob) {
// 生成图片
var newImg = document.createElement("img"),
url = URL.createObjectURL(blob);
newImg.onload = function() {
URL.revokeObjectURL(url);
};
obj.img == true
? newImg.src = canvas.toDataURL()
: newImg.src = url;
objThis.newImgObj = newImg;
// 创建表单数据
var formData = new FormData();
formData.append( obj.formName || 'forms',blob,obj.name || 'imgs' );
// 图片上传
var request = new XMLHttpRequest();
// obj.async ? obj.async = true : obj.async = false;
request.open( "POST",obj.url,true );
request.send( formData );
request.onreadystatechange = function() {
if ( request.readyState == 4 && request.status == 200 ) {
if( obj.dataType=="JSON" || obj.dataType=="json" ){
try{
objThis.success( JSON.parse(request.responseText) )
}catch( err ){
console.info( "banfeng reminds you: Error in converting received data to 'JSON' format" )
}
}else{
objThis.success( request.responseText )
}
}
};
},
obj.file.type || 'image/png',
);
},
explain:function(){
console.group( "This is uploadThumbnail" );
console.log( 'new uploadThumbnail({' +
'\n\tname:imgFileName || "imgs",' +
'\n\tformName:formName || "forms",' +
'\n\tmax:[maxWidth,maxHeight] || [ 400*400 ],' +
'\n\tfile:inputFile,' +
'\n\turl:URL,' +
'\n\tdataType:"json" || "text"' +
'\n\tsuccess:functon(data){} Callback function on success' +
'\n});' +
"\nobj.newImgObj:Compressed image object" )
console.groupEnd();
}
}
win.uploadThumbnail = uploadThumbnail;
}(window));
javaScript:压缩图片并上传的更多相关文章
- 使用canvas压缩图片 并上传
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结
相册 iphone的相册包含摄像头胶卷+用户计算机同步的部分照片.用户可以通过UIImagePickerController类提供的交互对话框来从相册中选择图像.但是,注意:相册中的图片机器路径无法直 ...
- HTML5 Canvas前台压缩图片并上传到服务器
1.前台代码: <input id="fileOne" type="file" /> <input id="btnOne" ...
- html5压缩图片并上传
手机端图片有很大的,上传的时候很慢,这时候就要压缩一下了,有一个开源的js可以压缩图片的大小,开源地址如下:https://github.com/think2011/localResizeIMG3 代 ...
- js压缩图片并上传,不失真,保证图片清晰度
<!DOCTYPE HTML> <html lang="zh-CN"> <head> <meta charset="UTF-8& ...
- Xamarin.Android 压缩图片并上传到WebServices
随着手机的拍照像素越来越高,导致图片赞的容量越来越大,如果上传多张图片不进行压缩.质量处理很容易出现OOM内存泄漏问题. 最近做了一个项目,向webservices上传多张照片,但是项目部署出来就会出 ...
- 微信小程序 压缩图片并上传
转自https://segmentfault.com/q/1010000012507519 wxml写入 <view bindtap='uploadImg'>上传</view> ...
- 微信小程序压缩图片并上传到服务器(拿去即用)
这里注意一下,图片压缩后的宽度是画布宽度的一半 canvasToTempFilePath 创建画布的时候会有一定的时间延迟容易失败,这里加setTimeout来缓冲一下 这是单张图片压缩,多张的压缩暂 ...
- 利用WebUploader进行图片批量上传,在页面显示后选择多张图片压缩至指定路径【java】
WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件.在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览 ...
随机推荐
- 去掉win7快捷方式小箭头
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons" ...
- 【Jest】笔记一:环境配置
一.开发环境 Mac node.js:v9.9.0 下载链接:http://nodejs.cn/download/ VScode 下载链接:https://code.visualstudio.com ...
- 经典问题----拓扑排序(HDU2647)
题目简介:有个工厂的老板给工人发奖金,每人基础都是888,工人们有自己的想法,如:a 工人想要比 b 工人的奖金高,老板想要使花的钱最少 那么就可以 给b 888,给a 889 ,但是如果在此基础上, ...
- C语言学习笔记之位运算求余
我们都知道,求一个数被另一个数整除的余数,可以用求余运算符”%“,但是,如果不允许使用求余运算符,又该怎么办呢?下面介绍一种方法,是通过位运算来求余,但是注意:该方法只对除数是2的N次方幂时才有效. ...
- Java(异常、枚举)
异常 在程序执行过程中由于设计或设备原因导致的程序中断的异常现象叫做异常 在try-catch-finally代码块中,finally是一定会执行的部分,如果finally中有return部分,则一定 ...
- 芯灵思Sinlinx A64开发板Linux内核定时器编程
开发平台 芯灵思Sinlinx A64 内存: 1GB 存储: 4GB 开发板详细参数 https://m.tb.cn/h.3wMaSKm 开发板交流群 641395230 Linux 内核定时器是内 ...
- 创建一个dynamics 365 CRM online plugin (五) - Images in Plugin
Snapshots of the primary entity's attributes from database before(pre) and after (post) the core pla ...
- centos7配置iscsi
什么是ISCSI iscsi--internet small computer system interface互联小型计算机系统接口,将数据包封装在TCP/IP协议中传输,使用普通网线和网络设备即可 ...
- MySQL 5.7版本 sql_mode=only_full_group_by 问题
具体错误: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in ...
- SQL脚本--总耗CPU最多的前个SQL --平均耗CPU最多的前个SQL
--总耗CPU最多的前个SQL SELECT TOP 20 total_worker_time/1000 AS [总消耗CPU 时间(ms)],execution_count [运行次数], qs.t ...