/** * 圖片壓縮上傳 * @param $im,圖片資源 * @param int $maxwidth,最大寬度,超過這個寬度則進行壓縮 * @param int $maxheight,最大高度,超過這個高度則進行壓縮 * @param $name,圖片名,完整的路徑加名稱 * @param $filetype,圖片類型 * @return bool */ function thumbImage($im,$name,$filetype,$maxwidth=800,$maxheight=920) { switch ($filetype) { case 'image/jpg': case 'image/jpeg': $im = imagecreatefromjpeg($im); //PHP圖片處理系統函數 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圖片處理系統函數 imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP圖片處理系統函數 } else { $newim = imagecreate($newwidth,$newheight); imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); } switch ($filetype) { case 'image/jpg' : 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/jpg' : 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; } /** * 圖片不改變長寬嗎,壓縮清晰度 * @param $img,'http://www.phpernote.com/images/logo.png' 或者 public/timg.jpg * @param $path, public/frontend/xxx.jpg 保存新圖片的地址 */ function dirthumbImage($img,$filename,$quality=20){ $imgInfo = pathinfo($img); $filetype = $imgInfo['extension']; switch ($filetype) { case 'gif': $image = imagecreatefromgif($img); header("Content-type:image/gif"); break; case 'png': $image = imagecreatefrompng($img); header("Content-type:image/png"); break; case 'wbmp': $image = imagecreatefromwbmp($img); header("Content-type:image/wbmp"); break; default: $image=imagecreatefromjpeg($img); //PHP圖片處理系統函數 jpg、jpeg header("Content-type:image/jpeg"); } if(empty($filename)) $filename=$img;//如果儲存文件為空,那么替換原來的文件 imagejpeg($image,$filename,$quality); //注意后面那個數字0,這里即壓縮等級,參數范圍:0-9*/ imagedestroy($image); } /** * 將base64編碼轉換為圖片保存至指定位置 * @param $dir,保存的路徑public/frontend/uplode/user * @param $filename,圖片的名稱 * @param $base64,圖片base64編碼 * @param $typeList,允許的圖片類型 'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF' * @return array */ function saveBase64($dir,$filename,$base64,$typeList){ header('Content-type:text/html;charset=utf-8'); preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result); $type = $result[2]; //獲取圖片的類型jpg png等 if(empty($typeList)) $typeList = [ 'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF'];//文件允許的類型 if(!in_array($type,$typeList)){ return array('error'=>2,'msg'=>'圖片格式錯誤'); } $name =$filename.'.'.$type; //圖片重命名 $savepath = $dir.'/'.$name; //圖片保存目錄 if(file_put_contents($savepath, base64_decode(str_replace($result[1], '', $base64)))) { //對圖片進行解析並保存 return array('error'=>0,'msg'=>'保存成功','file_path'=>$savepath); }else{ return array('error'=>1,'msg'=>'保存失敗'); } } function imgToBase64($img_file) { $img_base64 = ''; if (file_exists($img_file)) { $app_img_file = $img_file; // 圖片路徑 $img_info = getimagesize($app_img_file); // 取得圖片的大小,類型等 //echo '<pre>' . print_r($img_info, true) . '</pre><br>'; $fp = fopen($app_img_file, "r"); // 圖片是否可讀權限 if ($fp) { $filesize = filesize($app_img_file); $content = fread($fp, $filesize); $file_content = chunk_split(base64_encode($content)); // base64編碼 switch ($img_info[2]) { //判讀圖片類型 case 1: $img_type = "gif"; break; case 2: $img_type = "jpg"; break; case 3: $img_type = "png"; break; } $img_base64 = $file_content;//合成圖片的base64編碼 } fclose($fp); } return $img_base64; //返回圖片的base64 }
/**
* 獲取圖片的Base64編碼(不支持url)
* @param $img_file 傳入本地圖片地址
* @return string
*/
function imgToBase64($img_file) {
$img_base64 = '';
if (file_exists($img_file)) {
$app_img_file = $img_file; // 圖片路徑
$img_info = getimagesize($app_img_file); // 取得圖片的大小,類型等
//echo '<pre>' . print_r($img_info, true) . '</pre><br>';
$fp = fopen($app_img_file, "r"); // 圖片是否可讀權限
if ($fp) {
$filesize = filesize($app_img_file);
$content = fread($fp, $filesize);
$file_content = chunk_split(base64_encode($content)); // base64編碼
switch ($img_info[2]) { //判讀圖片類型
case 1: $img_type = "gif";
break;
case 2: $img_type = "jpg";
break;
case 3: $img_type = "png";
break;
}
$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成圖片的base64編碼
}
fclose($fp);
}
return $img_base64; //返回圖片的base64
}
JS前台壓縮
//圖片上傳
function b(obj,id) {
var r= new FileReader();
f=document.getElementById(id).files[0];
if(f==undefined){return false;}
r.readAsDataURL(f);
r.onload=function (e) {
//圖片壓縮
// 調用函數處理圖片
dealImage(this.result, {
// 注意:在pc端可以用絕對路徑或相對路徑,移動端最好用絕對路徑(因為用take photo后的圖片路徑,我沒有試成功(如果有人試成功了可以分享一下經驗))
width : 800
}, function(base){
//直接將獲取到的base64的字符串,放到一個image標簽中就可看到測試后的壓縮之后的樣式圖了
console.log("壓縮后:" + base.length / 1024 + " " + base);
});
};
}
/**
* 圖片壓縮,默認同比例壓縮
* @param {Object} path
* pc端傳入的路徑可以為相對路徑,但是在移動端上必須傳入的路徑是照相圖片儲存的絕對路徑
* @param {Object} obj
* obj 對象 有 width, height, quality(0-1)
* @param {Object} callback
* 回調函數有一個參數,base64的字符串數據
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默認按比例壓縮
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.9; // 默認圖片質量為0.5
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 創建屬性節點
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);
// 圖像質量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所繪制出的圖像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality );
// 回調函數返回base64的值
callback(base64);
}
}
