網(wǎng)上看了一些資料,關(guān)于處理圖片壓縮的,找到的大部分是單圖壓縮的,要么是單前端或者后端的,所以就自己整了下前后端壓縮,并支持多圖的壓縮圖片實(shí)例。代碼有點(diǎn)多,直接復(fù)制到編輯器看會比較清楚
!DOCTYPE html>
html>
head>
meta charset="UTF-8">
meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
title>實(shí)名驗(yàn)證/title>
script type="text/javascript">
/*
三個參數(shù)
file:一個是文件(類型是圖片格式),
w:一個是文件壓縮的后寬度,寬度越小,字節(jié)越小
objDiv:一個是容器或者回調(diào)函數(shù)
photoCompress()
*/
function photoCompress(file,w,objDiv){
var ready=new FileReader();
/*開始讀取指定的Blob對象或File對象中的內(nèi)容. 當(dāng)讀取操作完成時,readyState屬性的值會成為DONE,如果設(shè)置了onloadend事件處理程序,則調(diào)用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內(nèi)容.*/
ready.readAsDataURL(file);
ready.onload=function(){
var re=this.result;
canvasDataURL(re,w,objDiv)
}
}
function canvasDataURL(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默認(rèn)按比例壓縮
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默認(rèn)圖片質(zhì)量為0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 創(chuàng)建屬性節(jié)點(diǎn)
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 圖像質(zhì)量
if(obj.quality obj.quality = 1 obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所繪制出的圖像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回調(diào)函數(shù)返回base64的值
callback(base64);
}
}
/**
* 將以base64的圖片url數(shù)據(jù)轉(zhuǎn)換為Blob
* @param urlData
* 用url方式表示的base64圖片數(shù)據(jù)
*/
function convertBase64UrlToBlob(urlData){
var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
var xhr;
//上傳文件方法
function uploadClick() {
document.getElementsByClassName("uploadbtn")[0].value = '上傳中...';
document.getElementsByClassName("uploadbtn")[0].disabled=true;
var obj = document.getElementsByClassName("myfile");
for(var i=0;i2;i++){
UploadFile(obj[i].files[0],'file'+i);
}
}
function UploadFile(fileObj,filed){
var shopid = document.getElementById('shopid').value;
var adminid = document.getElementById('adminid').value;
var url = "newshimingupload.php"; // 接收上傳文件的后臺地址
var form = new FormData(); // FormData 對象
if(fileObj.size/1024 > 100) { //大于100k,進(jìn)行壓縮上傳
photoCompress(fileObj, {
quality: 0.2
}, function(base64Codes){
//console.log("壓縮后:" + base.length / 1024 + " " + base);
var bl = convertBase64UrlToBlob(base64Codes);
form.append("file", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件對象
form.append("shopid", shopid); // 文件對象
form.append("adminid", adminid); // 文件對象
form.append("filed", filed); // 文件對象
xhr = new XMLHttpRequest(); // XMLHttpRequest 對象
xhr.open("post", url, false); //post方式,url為服務(wù)器請求地址,true 該參數(shù)規(guī)定請求是否異步處理。
xhr.onload = uploadComplete; //請求完成
xhr.onerror = uploadFailed; //請求失敗
// xhr.upload.onprogress = progressFunction;//【上傳進(jìn)度調(diào)用方法實(shí)現(xiàn)】
xhr.upload.onloadstart = function(){//上傳開始執(zhí)行方法
ot = new Date().getTime(); //設(shè)置上傳開始時間
oloaded = 0;//設(shè)置上傳開始時,以上傳的文件大小為0
};
xhr.send(form); //開始上傳,發(fā)送form數(shù)據(jù)
});
}else{ //小于等于1M 原圖上傳
form.append("file", fileObj); // 文件對象
form.append("shopid", shopid); // 文件對象
form.append("adminid", adminid); // 文件對象
form.append("filed", filed); // 文件對象
xhr = new XMLHttpRequest(); // XMLHttpRequest 對象
xhr.open("post", url, false); //post方式,url為服務(wù)器請求地址,true 該參數(shù)規(guī)定請求是否異步處理。
xhr.onload = uploadComplete; //請求完成
xhr.onerror = uploadFailed; //請求失敗
xhr.upload.onloadstart = function(){//上傳開始執(zhí)行方法
ot = new Date().getTime(); //設(shè)置上傳開始時間
oloaded = 0;//設(shè)置上傳開始時,以上傳的文件大小為0
};
xhr.send(form); //開始上傳,發(fā)送form數(shù)據(jù)
}
}
//上傳成功響應(yīng)
function uploadComplete(evt) {
//服務(wù)斷接收完文件返回的結(jié)果
var data = JSON.parse(evt.target.responseText);
console.log(data);
if(data.status){
alert(data.msg);
if(data.msg == '門店照上傳成功'){
window.location.href = "/dd_admin/index.php";
}
}
}
//上傳失敗
function uploadFailed(evt) {
alert("網(wǎng)絡(luò)不穩(wěn)定,請重新上傳!");
}
/script>
/head>
body>
style type="text/css">
.main{text-align: center;padding-top: 50px;}
.main .myfile{margin-bottom: 15px;}
/style>
div class="main">
營業(yè)執(zhí)照:
input type="file" class="myfile" id="file1" name="file1" accept="image/x-png, image/jpg, image/jpeg, image/gif"/>br>
門店照:
input type="file" class="myfile" id="file2" name="file2" accept="image/x-png, image/jpg, image/jpeg, image/gif"/>br>
input type="hidden" id="shopid" name="shopid" value="?php echo $_GET['shopid']; ?>" maxlength="15">
input type="hidden" id="adminid" name="adminid" value="?php echo $_GET['adminid']; ?>" maxlength="15">
input style="margin-top: 25px;" class="uploadbtn" type="button" onclick="uploadClick()" value="上傳" />br>
/div>
/body>
/html>
2、前端圖片壓縮后,請求到自定義的接口upload_deal.php.代碼如下
?php
require_once('public_func.php');
actionUpload('uploads/','file'); //參數(shù)分別代表圖片存儲的路徑和上傳的文件名
}
3、在第二部引入public_func.php,這塊代碼主要是對后端處理圖片壓縮
function actionUpload($path = '/uploads/',$filename='myFile')
{
// $path = 'uploads/'; //圖片存放根目錄 根據(jù)自己項(xiàng)目路徑而定
$file = $_FILES[$filename]['name'];
$folder = $path.date('Ymd')."/";
$pre = rand(999,9999).time();
$ext = strrchr($file,'.');
$newName = $pre.$ext;
$out = array(
'msg'=>'',
'status'=>'error',
'img_url'=>''
);
if(!is_dir($folder))
{
if(!mkdir($folder, 0777, true)){
$out['msg'] = '圖片目錄創(chuàng)建失??!';
echo json_encode($out);
exit;
}
}
$im = $_FILES[$filename]['tmp_name']; //上傳圖片資源
$maxwidth="1056"; //設(shè)置圖片的最大寬度
$maxheight="500"; //設(shè)置圖片的最大高度
$imgname = $folder.$newName; //圖片存放路徑 根據(jù)自己圖片路徑而定
$filetype=$_FILES[$filename]['type'];//圖片類型
$result = thumbImage($im,$maxwidth,$maxheight,$imgname,$filetype);
if($result){
$out['msg'] = '圖片上傳成功';
$out['status'] = 'success';
$out['img_url'] = $folder.$newName;
}else{
$out['msg'] = '圖片上傳失敗';
}
return json_encode($out);
exit;
}
//壓縮圖片
function thumbImage($im,$maxwidth,$maxheight,$name,$filetype)
{
switch ($filetype) {
case 'image/pjpeg':
case 'image/jpeg':
$im = imagecreatefromjpeg($im); //PHP圖片處理系統(tǒng)函數(shù)
break;
case 'image/gif':
$im = imagecreatefromgif($im);
break;
case 'image/png':
$im = imagecreatefrompng($im);
break;
case 'image/wbmp':
$im = imagecreatefromwbmp($im);
break;
}
$resizewidth_tag = $resizeheight_tag = false;
$pic_width = imagesx($im);
$pic_height = imagesy($im);
if(($maxwidth $pic_width > $maxwidth) || ($maxheight $pic_height > $maxheight))
{
$resizewidth_tag = $resizeheight_tag = false;
if($maxwidth $pic_width>$maxwidth)
{
$widthratio = $maxwidth / $pic_width;
$resizewidth_tag = true;
}
if($maxheight $pic_height>$maxheight)
{
$heightratio = $maxheight / $pic_height;
$resizeheight_tag = true;
}
if($resizewidth_tag $resizeheight_tag)
{
if($widthratio $heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if($resizewidth_tag !$resizeheight_tag)
$ratio = $widthratio;
if($resizeheight_tag !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if(function_exists("imagecopyresampled"))
{
$newim = imagecreatetruecolor($newwidth,$newheight);//PHP圖片處理系統(tǒng)函數(shù)
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP圖片處理系統(tǒng)函數(shù)
}
else
{
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
switch ($filetype) {
case 'image/pjpeg' :
case 'image/jpeg' :
$result = imagejpeg($newim,$name);
break;
case 'image/gif' :
$result = imagegif($newim,$name);
break;
case 'image/png' :
$result = imagepng($newim,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($newim,$name);
break;
}
imagedestroy($newim);
}
else
{
switch ($filetype) {
case 'image/pjpeg' :
case 'image/jpeg' :
$result = imagejpeg($im,$name);
break;
case 'image/gif' :
$result = imagegif($im,$name);
break;
case 'image/png' :
$result = imagepng($im,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($im,$name);
break;
}
}
return $result;
}
以上所述是小編給大家介紹的php處理多圖上傳壓縮代碼功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!