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浏览 ...
随机推荐
- Redis不支持ssl
一直在公司内部推荐redis做cache管理,今天偶然想起虽然C#没问题,可是c/c++没查过可不可行. 结果查了一下,还真tmd有问题,官方的c client版本只支持linux side的,根本没 ...
- [原] inline operator delete & DLL boundary
很久以前写在百度空间的这篇文章: [百度空间] [原] 全局operator delete重载到DLL 首先,纠正一个词“重载”,operator new/delete是替换(replacement) ...
- Flutter Inspector 功能:Toggle Platform,Show Debug Paint,Show Paint Baselines
Flutter Inspector 功能 说明 Toggle Platform 切换操作系统(Android.iOS) Show Debug Paint Show Paint Baselines Wi ...
- javascript中的立即执行函数的原理
形如 ((function Test(a) { //code here... })('Hello')); 被称作立即执行函数. 首先需要了解的是,这并不是一种hack,这是javascript的基本语 ...
- maven:Fatal error compiling: 无效的目标 发行版: 1.8 -> [Help 1]
https://blog.csdn.net/kkgbn/article/details/72777750
- 关于FIFO异步复位的问题
关于FIFO异步复位的问题 FIFO异步复位的宽度,需要保证至少3个较慢时钟的时钟周期长度. 怎样对一个脉冲加宽呢? `timescale 1ns / 1ps //////////////////// ...
- 更新 TeX Live 软件包
这个 TeX Live 软件,你得时常更新一下,不然会遇到一些由软件包自身 Bug 导致的编译问题.比如,这次我使用 Beamer 软件包写演示文稿,就遇到问题了,结果发现是软件包自身存在的问题.安装 ...
- 51nod1227 平均最小公倍数
$Ans(l,r)=ans(r)-ans(l-1)\\ans(n)=\sum\limits_{i=1}^n \sum\limits_{j=1}^i \frac{j}{gcd(i,j)}\\=\sum\ ...
- listview-android:打造万能通用适配器(转)
转载:https://blog.csdn.net/q649381130/article/details/51781921: 1.前言 listview作为安卓项目中一个的明星控件,它的适配器的写法是广 ...
- [UE4]引用Grabbable接口
一.当前:可抓取对象的类型是GrabTargetActor 二.修改目标:可抓取对象的类型改成Grabbable. 1.Fand Grab Target的返回值改成Grabbale(变量的数据类型可以 ...