javaScript:压缩图片并上传

Posted 半封

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 ){
                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:压缩图片并上传的主要内容,如果未能解决你的问题,请参考以下文章

移动端压缩并ajax上传图片解决方案

多张图片上传并压缩

java上传图片并压缩图片大小

前端通过canvas实现图片压缩

Java实现的上传并压缩图片功能可等比例压缩或原尺寸压缩

前端压缩并上传图片