Jquery+HTML5+PHP實現前臺壓縮圖片並上傳
阿新 • • 發佈:2018-12-25
先上圖吧:
待上傳
上傳後
功能描述:
使用HTML5在前臺進行圖片壓縮,然後上傳至伺服器上由PHP儲存。此外掛只適用於PC端,未做手機端頁面優化,如果需要應用在手機端請自行優化UI,即然是PC端為什麼還要前端壓縮呢?PC端很容易使用圖片處理軟體進行壓縮,那是適用於有會PS,會光影魔術手的人。但還有很多小白,他們就是簡單的拿手機或相機拍了照就是要上傳的,他樣不想或不會或工作流程問題無法處理圖片。好了,廢話不說上程式碼。
PHP端程式碼
<?php //接收base64格式圖片 $postIMG = $_POST['image']; $fileName = date('YmdHis') .'-'. mt_rand(100,999); $imgPath = './uploads/'. $fileName . '.jpg'; $data = base64_decode($postIMG); $fp = fopen($imgPath,'w'); fwrite($fp,$data); fclose($fp); $info = '上傳成功'; $status ='1'; $url = '/js_upload/uploads/'.$fileName . '.jpg'; //請根據你的實際情況設定返回的路徑 $return = array('info'=>$info,'status'=>$status,'url'=>$url); echo json_encode($return);
JavaScript核心程式碼:部分程式碼來自網上
/** H5u Html5客戶端壓縮圖處並上傳,服務端php接收base64編碼圖片並儲存 */ (function($){ $.fn.extend({ aiiUpload:function(obj) { if(typeof obj !="object") { alert('引數錯誤'); return; } var imageWidth,imageHeight; var base64; var file_num=0; var fileInput=$(this); var fileInputId=fileInput.attr('id'); var randID = Math.floor(Math.random()*1000); //隨機ID createDoc('#'+fileInputId,obj.method,obj.action,obj.subText,randID,obj.formIdName); $('#h5u_file_'+ randID).change(function(){ if(test(this.value)==false) { alert('格式錯誤'); return; } var objUrl = getObjectURL(this.files[0]); if (objUrl) { //imgBefore(objUrl,file_num); render(objUrl,obj.max_w,obj.max_h,file_num,randID,obj.action); file_num++; } }); } }); //建立form表單 function createDoc(objID,form_method,form_action,sub_txt,rand_id,form_id_name) { var element=$(objID); //element.append('<ul class="viewList"></ul>').append('<div class="fileBox"><input type="file" id="aii_file" /><div class="file_bg"></div></div>').append('<form id="aii_upload_form" method="'+form_method+'" action="'+form_action+'"></form>').append('<canvas id="canvas"></canvas>'); var str = '<div class="upbox3"><canvas id="canvas_'+ rand_id +'"></canvas><div class="options hide" id="h5u_options_'+ rand_id +'"><a class="btn-del" id="h5u_del_'+ rand_id +'">刪除</a><a class="btn-big" id="h5u_big_'+ rand_id +'">放大</a></div><img src="" id="h5u_preview_'+ rand_id +'"/><div class="js-upbtn" id="h5u_upbtn_'+ rand_id +'"><a href="javascript:;" class="h5u_file"><input type="file" class="up_file3" id="h5u_file_'+ rand_id +'" accept="image/*">+上傳附件</a><p class="a-behind">'+ sub_txt +'</p></div><input type="hidden" name="'+ form_id_name +'" id="h5u_form_hidden_'+ rand_id +'" ><div class="status hide" id="h5u_status_'+ rand_id +'"></div></div>'; element.append(str); //放大 $("#h5u_big_"+ rand_id).click(function(){ alert('big'+ rand_id) }); //刪除1.img.src = '', 2.hidden.val = '',3.show upbtn,hide options,4. status.hide $("#h5u_del_"+ rand_id).click(function(){ $("#h5u_preview_"+ rand_id).attr('src',''); $("#h5u_form_hidden_"+ rand_id).val(''); $("#h5u_options_"+ rand_id).hide(); $("#h5u_upbtn_"+rand_id).show(); $("#h5u_status_"+ rand_id).hide(); }); } //檢查檔案類是否是圖片格式 function test(value) { var regexp=new RegExp("(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$",'g'); return regexp.test(value); } function render(src,MaximgW,MaximgH,idnum,rand_id,action) { console.log('rand_id',rand_id); var image=new Image(); image.onload=function() { //如果圖片的尺寸小於定義的最大寬和高,則以圖片原始尺寸為準 var canvas=document.getElementById('canvas_'+ rand_id); var previewIMG = document.getElementById('h5u_preview_'+ rand_id); //預覽圖片 previewIMG.src = src; if(image.width < MaximgW && image.height < MaximgH){ imageWidth = image.width; imageHeight = image.height; }else{ if(image.width>image.height) { imageWidth=MaximgW; imageHeight=MaximgW*(image.height/image.width); } else if(image.width<image.height) { imageHeight=MaximgH; imageWidth=MaximgH*(image.width/image.height); } else { imageWidth=MaximgW; imageHeight=MaximgH; } } canvas.width=imageWidth; canvas.height=imageHeight; var con=canvas.getContext('2d'); con.clearRect(0,0,canvas.width,canvas.height); con.drawImage(image,0,0,imageWidth,imageHeight); base64=canvas.toDataURL('image/jpeg',0.5).substr(22); //add_doc(base64,idnum); //上傳圖片 upload_base(base64,action,rand_id); } image.src=src; }; //建立一個可存取到該file的url function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } //預覽 function imgBefore(objUrl,idnum) { var li='<li class="view"><img src="'+objUrl+'" id="aiiImg_'+idnum+'" idnum="'+idnum+'" /><div class="close" onclick="img_remove(this);"></div></li>' $('.viewList').append(li); var img=$('#aiiImg_'+idnum); //預覽圖片居中 填滿 程式碼 //console.log('asdfasdfasdf'); img.load(function(){ var imgw=img.width(), imgh=img.height(); console.log(imgw); console.log(imgh); if(imgw>imgh) { img.css('height','100%'); img.css('width','auto'); img.css('marginLeft',-(img.width()-img.height())/2+'px'); } else if(imgw<imgh) { img.css('width','100%'); img.css('height','auto'); img.css('marginTop',-(img.height()-img.width())/2+'px'); } }); } //上傳圖片 function upload_base(base,action,rand_id){ //隱藏上傳控制元件按鈕 $('#h5u_status_'+ rand_id).html('準備上傳').addClass('normal'); $.post(action,{image:base},function(json){ console.log(json); if(json.status == 1){ $("#h5u_form_hidden_"+ rand_id).val(json.url); //表單 $('#h5u_upbtn_'+ rand_id).hide(); $('#h5u_options_'+ rand_id).show(); $('#h5u_status_'+ rand_id).html('上傳成功').addClass('success').removeClass('normal').show(); }else{ $('#h5u_status_'+ rand_id).html(json.info).addClass('error').removeClass('normal').show(); } },'json'); } function add_doc (base,idnum) { $('#aii_upload_form').append('<input type="hidden" name="img[]" id="f_'+idnum+'" value="'+base+'"/>'); } })(jQuery); function img_remove(element) { var num=$(element).prev().attr('idnum'); $(element).parent().remove(); $('#f_'+num).remove(); console.log('asdf'); }
HTML呼叫程式碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Jquery + html 5 + canvas實現圖片上傳</title> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="js/h5Upload.js"></script> <link rel="stylesheet" type="text/css" href="js/h5Upload.css"> </head> <body> <!-- <div class="upbox3"> <div class="options"> <a class="btn-del">刪除</a> <a class="btn-big">放大</a> </div> <img src="https://img.alicdn.com/imgextra/i1/2454021808/TB2IPQAXeYCK1JjSZFmXXbCyVXa_!!2454021808-0-beehive-scenes.jpg_180x180q90.jpg_.webp" /> <a href="javascript:;" class="h5u_file"> <input type="file" accept="image/*">+上傳附件 </a> <p class="a-behind">單位證件</p> </div> --> <style> .section{height:200px;} </style> <section class="section"> <div id="box"></div> </section> <div class="content"> <h2>營業執照</h2> <div id="box2"></div> </div> <script type="text/javascript"> $('#box').aiiUpload({ action:'upload.php', max_w:800, max_h:1000, subText:'單位證件', formIdName:'id_card', //表字段名稱 //fileText:'選擇圖片' }); $('#box2').aiiUpload({ action:'upload.php', //後臺接收圖片地址 max_w:800, //壓縮圖片的最大寬度,低於此寬度不會被壓縮 max_h:1000, //壓縮圖片的最大高度,低於此高度的圖片不會被壓縮 subText:'營業執照', //上傳控制元件上顯示的上傳標籤名稱 formIdName:'id_card2', //表字段名稱 //fileText:'選擇圖片' }); </script> </body> </html>
下載地址: http://download.csdn.net/download/hotlinhao/10038799