1. 程式人生 > >laravel 圖片壓縮與上傳原生程式碼,

laravel 圖片壓縮與上傳原生程式碼,

/**
 * 上傳騰訊雲伺服器圖片
* @return array
 */
function compression_upload_cos(Illuminate\Http\Request $request,$type)
{
$appid = config('file.tengxun_cos.appid');
$region = config('file.tengxun_cos.region');
$bucket = config('file.tengxun_cos.bucket');
$SecretId = config('file.tengxun_cos.SecretId');
$SecretKey 
= config('file.tengxun_cos.SecretKey'); $Folder = config('file.Folder.'.$type); if ($request->hasFile('file')) { $image = $request->file('file'); $cosClient = new Client( array( 'region' => $region, 'credentials' => array( 'appId' => $appid, 'secretId' => $SecretId, 'secretKey' =>
$SecretKey ) ) ); //定義引數 $result = []; $data = []; $newarray = config('file.'.$type);//獲取縮放陣列 list($width,$height) = getimagesize($image->getRealPath());//獲取圖片長寬賦值 array_unshift($newarray,array("width"=>$width,"height"=>$height));//填充陣列 $src = @imagecreatefromjpeg ($image->getRealPath
());//獲取圖片檔案流 foreach($newarray as $k => $v){ $new_name = time() . '_' . rand(1000000, 9999999) . '.' . $image->getClientOriginalExtension();//新命名 //這裡進行圖片壓縮,目前只壓縮png/jpg格式 if($image->getClientMimeType() == "image/png"){ $tmp = imagecreatetruecolor($v['width'],$v['height']);//生成畫布 imagecopyresized($tmp, $src, 0, 0, 0, 0, $v['width'], $v['height'], $width, $height);//速度快質量差 //imagecopyresampled($tmp, $src, 0, 0, 0, 0, $v['width'], $v['height'], $width, $height);//速度慢質量高 imagepng($tmp, $image->getRealPath(),7); imagedestroy($tmp); }else if ($image->getClientMimeType() == "image/jpeg") { $tmp = imagecreatetruecolor($v['width'],$v['height']);生成畫布 imagecopyresized($tmp, $src, 0, 0, 0, 0, $v['width'], $v['height'], $width, $height);//速度快質量差 //imagecopyresampled($tmp, $src, 0, 0, 0, 0, $v['width'], $v['height'], $width, $height);//速度慢質量高 imagejpeg($tmp, $image->getRealPath(),75);//壓縮後的檔案,寫入快取檔案內 imagedestroy($tmp);//清除生成檔案 } $result_upload = $cosClient->putObject( array( 'Bucket' => $bucket, 'Key' => $Folder.$new_name, 'Body' => file_get_contents($image->getRealPath())//獲取檔案資料流傳送到騰訊雲 ) ); $res['src_hash'] = str_replace('"','',$result_upload['ETag']); $res['file_name'] = $new_name; $res['file_path'] = urldecode($result_upload['ObjectURL']); $res['file_size'] = getUriLen(urldecode($result_upload['ObjectURL'])); $res['original_name'] = $image->getClientOriginalName(); $res['mimeType'] = $image->getClientMimeType(); $result[] = $res; $data[] = urldecode($res['file_path']); } $response = array( 'status' => 200, 'errno' => 0, 'message' => '上傳成功', 'result'=>$result, 'data' => $data ); } else { $response = array( 'status' => 500, 'message' => '請選擇要上傳的檔案' ); } return $response;

}

//file檔案配置

'goods' => [
    ["width"=>1424,"height"=>878],
["width"=>300,"height"=>300],
["width"=>230,"height"=>230],
],
'shop' => [
    ["width"=>190,"height"=>190],
["width"=>146,"height"=>146]
],
'member' => [
    ["width"=>200,"height"=>200]
],
'Folder' => [
'goods'=>'goods/',
'shop'=>'shop/',
'member'=>'member/',
]