码迷,mamicode.com
首页 > 编程语言 > 详细

javaScript:压缩图片并上传

时间:2018-11-23 12:37:09      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:xmlhttp   ase   缺省   宽度   onchange   页面   pre   post   amp   

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 ){
                var objThis = this;
                // 压缩图片需要的一些元素和对象
                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 )
                                }
                            }
                        }; 
                    }, 
                    file.type || ‘image/png‘,
                );

            },
            explain:function(){
                console.log( ‘new uploadThumbnail({‘ );
                console.log( ‘  name:imgFileName || "imgs",‘ );
                console.log( ‘  formName:formName || "forms",‘ );
                console.log( ‘  max:[maxWidth,maxHeight]  || [ 400*400 ],‘ );
                console.log( ‘  file:inputFile,‘ );
                console.log( ‘  url:URL,‘ );
                console.log( ‘  dataType:"json" || "text"‘ );
                console.log( ‘  success:functon(data){} Callback function on success‘ );
                console.log( ‘});‘ );
                console.log( "obj.newImgObj:Compressed image object" )
            }

        }
        win.uploadThumbnail = uploadThumbnail;
    }(window))

 

javaScript:压缩图片并上传

标签:xmlhttp   ase   缺省   宽度   onchange   页面   pre   post   amp   

原文地址:https://www.cnblogs.com/wannian/p/10006565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!