smelikecat

导航

[H5-Compress-Image]利用canvas实现 javascript 图片压缩处理_基于requirejs模块化的代码实现

// 还存在有问题的代码,问题在于processFile()中
// 问题:在ipone 5c 下,某些图片压缩处理后,上传到服务器生成的文件size为0,即是空白 ;define(['mod/tool/formSubmit'] ,function(o_formSubmit) { return { init: function(id) { var self = this; self.sniff(id); var $img = ''; var $inputField = ''; }, sniff: function(id) { var self = this; if (window.File && window.FileReader && window.FormData) { $inputField = $('#' + id); $inputField.on('change', function (e) { var file = e.target.files[0]; if($('.c-img-wrap').length >= 9) { Hnb.ui.showError('不能上传超过9张图片' , 3000); return ; } if (file) { //alert(file.type); //if(!file.type) file.type='image/jpeg'; //if (/^image\//i.test(file.type)) { if($("#id_img_list").parent().attr("scrollWidth") > $(window).width()) { $("#id_img_list").parent().scrollLeft($("#id_img_list").parent().attr("scrollWidth") - $(window).width()); } $img = $('<a class="bg c-img-wrap" href="javascript:void(null);"><i class="pa c-img-close"></i></a>').insertBefore($("#id_last_img_wrap")); self.readFile(file); //} else { // Hnb.ui.showError('请在浏览器中打开该页面上传图片' , 3000); // $inputField.val(''); //} } }); $inputField.val(''); } else { Hnb.ui.showError("当前您的浏览器不支持图片上传,请选择其他的浏览器进行上传。" , 3000); $inputField.val(''); } }, readFile: function (file) { var self = this; var reader = new FileReader(); var head = ''; reader.onloadend = function () { //reader.onload = function () { head = reader.result.substr(0, 20); alert('head:' + head); alert('file_type:' + file.type); self.processFile(reader.result, file.type); } reader.onerror = function () { Hnb.ui.showError('上传图片过程中发生了网络异常,请稍后重试。' , 3000); } reader.readAsDataURL(file); }, processFile: function (dataURL, fileType) { var self = this; var maxWidth = 3120; var maxHeight = 4208; var image = new Image(); image.src = dataURL; image.onload = function () { var width = image.width; var height = image.height; var shouldResize = (width > maxWidth) || (height > maxHeight); if (!shouldResize) { //self.submitFile(dataURL); self.sendFile(dataURL , fileType); return; } var newWidth; var newHeight; if (width > height) { newHeight = height * (maxWidth / width); newWidth = maxWidth; } else { newWidth = width * (maxHeight / height); newHeight = maxHeight; } var canvas = document.createElement('canvas'); canvas.width = newWidth; canvas.height = newHeight; var context = canvas.getContext('2d'); context.drawImage(this, 0, 0, newWidth, newHeight); dataURL = canvas.toDataURL(fileType); alert(dataURL.length); //window.location = dataURL; //self.sendFile(dataURL , fileType); /* var file = canvas.mozGetAsFile("foo.png"); var f = document.createElement("form"); var i = document.createElement("input"); //input element, text i.setAttribute('type',"file"); i.setAttribute('name',"upfile"); i.setAttribute('value' , dataURL); f.appendChild(i); */ //$("#id_upfile").val(dataURL); //document.forms[0].upfile.val = dataURL; //window.location = dataURL; //var formData = new FormData(document.forms[0]); //console.log(document.forms[0]); //console.log(formData.get('upfile')); //console.log(formData); //return; //formData.append('imageData', dataURL); //formData.delete('upfile'); //console.log($inputField.files); //formData.set('upfile', $inputField.files[0] , dataURL); //self.submitFile($(f)); }; image.onerror = function () { //alert('There was an error processing your file!'); Hnb.ui.showError('上传图片处理过程中发生了网络异常,请稍后重试。' , 3000); }; }, submitFile: function(f) { var self = this; //console.log(f); o_formSubmit.create(f , Hnb.WWW_CGI_URL + "/image/saveInCrossDomain").start().done(function(json_msg){ if(json_msg.state || !json_msg.data.real_url) { Hnb.ui.showError("上传图片失败!" , 3000); $img.remove(); } else { console.log(json_msg.data); $img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url); //$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">'); $("#id_top_wrap").addClass("active"); //$img.html(""); } }).fail(function(json_error){ $img.remove(); Hnb.ui.showError("您的网络有点慢,请稍后重试" , 3000); }).always(function(){ $img.removeClass("bg"); self.isSubmitingImgNum--; }); }, sendFile: function (fileData , fileType) { var formData = new FormData(); formData.append('imageData', fileData); formData.append('imageType' , fileType); $.ajax({ type: 'POST', timeout: 300000, url: Hnb.WWW_CGI_URL + '/image/saveCndCompressImage', data: formData, contentType: false, processData: false, success: function (json_msg) { //console.log('返回json数据' + json_msg); var json_msg = $.parseJSON(json_msg); if(!json_msg.state) { // 跨域请求处理 document.domain = 'hinabian.com'; // 可以将上传到线上的图片,追加到预览图位置 // ... } else { Hnb.ui.showError('您的网络有点慢,请稍后再上传。' , 3000); } }, error: function (json_msg) { Hnb.ui.showError('上传图片发生了网络异常,请稍后重试。' , 3000);; } }).always( function() { $inputField.val(""); $img.removeClass("bg"); } ); } } });

 

// 修改后,可以正常使用的代码

;define(['mod/tool/formSubmit'] ,function(o_formSubmit) {

    return {
        
        init: function(id) {
            var self = this;
            self.sniff(id);
            var $img = '';
            var $inputField = '';
        },
        sniff: function(id) {
            var self = this;
            if (window.File && window.FileReader && window.FormData) {
                
                $inputField = $('#' + id);
                $inputField.on('change', function (e) {
    
                    var file = e.target.files[0];
                    if($('.c-img-wrap').length >= 9)
                    {
                        Hnb.ui.showError('不能上传超过9张图片' , 3000);
                        return ;
                    }
                        
                    if (file) {
                        //if(!file.type) file.type='image/jpeg';
                        //if (/^image\//i.test(file.type)) {
                        if($("#id_img_list").parent().attr("scrollWidth") > $(window).width())
                        {
                            $("#id_img_list").parent().scrollLeft($("#id_img_list").parent().attr("scrollWidth") - $(window).width());
                        }
                        $img = $('<a class="bg c-img-wrap" href="javascript:void(null);"><i class="pa  c-img-close"></i></a>').insertBefore($("#id_last_img_wrap"));
                        
                        self.readFile(file);
                    }
                });
            } else {
                Hnb.ui.showError("当前您的浏览器不支持图片上传,请选择其他的浏览器进行上传。", 3000);
                //$inputField.val('');
            }
            $inputField.val('');
        },
        
        readFile: function (file) {
            var self = this;
            var reader = new FileReader();
            var head = '';
            reader.onloadend = function () {
            //reader.onload = function () {
                //head = reader.result.substr(0, 20);
                self.processFile(reader.result, file.type);
            }

            reader.onerror = function () {
                Hnb.ui.showError('上传图片过程中发生了网络异常,请稍后重试。', 3000);
                return;
            }

            reader.readAsDataURL(file);
            $inputField.val('');
        },
        
        processFile: function (dataURL, fileType) {
            var self = this;
            var unitSize = 480;

            var image = new Image();
            image.src = dataURL;

            image.onload = function () {
                var wFactor = image.width / unitSize;
                var hFactor = image.height / unitSize;
                var minFactor = Math.round(Math.min(wFactor, hFactor));

                if (minFactor < 2) {
                    //self.submitFile(dataURL);
                    self.sendFile(dataURL, fileType);
                    return;
                }

                var newWidth = image.width / minFactor;
                var newHeight = image.height / minFactor;
                var canvas = document.createElement('canvas');
                canvas.width = newWidth;
                canvas.height = newHeight;

                var context = canvas.getContext('2d');
                context.drawImage(this, 0, 0, newWidth, newHeight);

                dataURL = canvas.toDataURL(fileType);
                //window.location = dataURL;
                self.sendFile(dataURL, fileType);
            };

            image.onerror = function () {
                Hnb.ui.showError('上传图片处理过程中发生了网络异常,请稍后重试。' , 3000);
                $inputField.val('');
            };
        },
        
        submitFile: function(f) {
            var self = this;
            o_formSubmit.create(f , Hnb.WWW_CGI_URL + "/image/saveInCrossDomain").start().done(function(json_msg){
                if(json_msg.state || !json_msg.data.real_url) {
                    Hnb.ui.showError("上传图片失败!" ,  3000);
                    $img.remove();
                } else {
                    $img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url);
                    //$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">');
                    $("#id_top_wrap").addClass("active");
                    //$img.html("");
                }					
            }).fail(function(json_error){
                $img.remove();
                Hnb.ui.showError("您的网络有点慢,请稍后重试" , 3000);
            }).always(function(){
                $img.removeClass("bg");
                self.isSubmitingImgNum--;
                
            });		
        },        
        
        sendFile: function (fileData , fileType) {

            var formData = new FormData();
            formData.append('imageData', fileData);
            formData.append('imageType' , fileType);
            
            $.ajax({
                type: 'POST',
                timeout: 300000,
                url: Hnb.WWW_CGI_URL + '/image/saveCndCompressImage',
                data: formData,
                contentType: false,
                processData: false,
                success: function (json_msg) {
                    var json_msg = $.parseJSON(json_msg);
                    if(!json_msg.state)
                    {
                        document.domain = 'hinabian.com';
                        $img.removeClass("bg").addClass("comBg").css("background-image" , "url(" + json_msg.data.real_url + ")").attr("hnb-src" , json_msg.data.real_url);
						//$img.html('<img src="' + json_msg.data.real_url + '" alt="帖子图片">');
                        $("#id_top_wrap").addClass("active");
                    } else {
                        Hnb.ui.showError('您的网络有点慢,请稍后再上传。' , 3000);
                    }
                },
                error: function (json_msg) {
                     Hnb.ui.showError('上传图片发生了网络异常,请稍后重试。' , 3000);;
                }
            }).always(
                function() {
                    $inputField.val("");
                    $img.removeClass("bg");
                }
            );
        }
    }
});

 

posted on 2015-11-11 11:45  smelikecat  阅读(576)  评论(0编辑  收藏  举报