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浏览 ...
随机推荐
- 获取【请求体】数据的3种方式(精)(文末代码) request.getInputStream() request.getInputStream() request.getReader()
application/x- www-form-urlencoded是Post请求默认的请求体内容类型,也是form表单默认的类型.Servlet API规范中对该类型的请求内容提供了request. ...
- Python(三)——文件操作
在我们用语言的过程中,比如要往文件内进行读写,那么势必要进行文件操作,那么咋操作呢?用眼睛直接看么?今天就定个小目标,把文件读写那些事扯一扯 文件操作 把大象放进冰箱分几步? 第一步:打开冰箱 第二步 ...
- Redis入门的简单使用
Redis是什么? redis是一个开源的,面向键/值对的NOSQL的分布式数据库系统 NOSQL指的是非关系型的数据,简单直白地讲就是在非关系型的数据库中不存在表的概念,而是以键值对的方式, 即一个 ...
- 关于C6678的网口问题
1.C6678 Keystone1架构的GbE switch subsystem如图所示: 2.从图中可以看到MAC层与物理层PHY芯片的连接接口是由SGMII+SerDES构成,SGMII是以太网M ...
- Azure CosmosDB (6) 冲突类型和解决策略
<Windows Azure Platform 系列文章目录> 当我们为CosmosDB配置多个Azure Region写入,就需要考虑冲突类型和解决策略. 对于配置了多个写入区域的 Az ...
- 一本通之 一堆迷宫 (Dungeon Master&走出迷宫&走迷宫)
一本通在线崩溃....... . 有图有真相 这是个三维迷宫,其实和二位迷宫差不多,只是方向多加了2个. 但这个题的输入十分恶心,一度被坑的用cin.ignore(),但还是不过... 它的正确输入方 ...
- 配置中心Nacos
Nacos 是阿里巴巴2018年7月份开源的项目,如其名, Naming Configuration Service ,专注于服务发现和配置管理领域. Nacos 是什么?上面已经大概介绍了,更多详细 ...
- 关于mysql文件导入提示“Variable @OLD_CHARACTER_SET_CLIENT can't be set to the value of @@CHARACTER_SET_CLIENT”问题分析
今天用myssqldump导出数据,然后再导入另外mysql数据库时,提示Variable @OLD_CHARACTER_SET_CLIENT can't be set to the value of ...
- python使用itchat发送微信消息提醒
最近在学习一点python,先找了找有趣的应用,实际修改跑了一下提高兴趣程度. 找到itchat,它的简介是这样的: “itchat是一个开源的微信个人号接口,使用python调用微信从未如此简单. ...
- Windows Unity ARKit发布到IOS相关设置及错误解决
Windows 版Unity安装: 考虑到在虚拟机中运行Unity比较卡,所以采用在Windows Unity上将项目发布好然后再复制到Mac虚拟机中通过XCode进行编译的方式. Unity版本为 ...