本文目錄一覽:
- 1、php等比縮放圖片,就是只按寬度縮小圖片,當圖片寬度大於750時就縮小到750 高度不用管 跟着寬度縮就行了
- 2、求php圖片縮放處理函數
- 3、php圖片可以等比例的縮放嗎
- 4、php實現圖片等比例縮放代碼
php等比縮放圖片,就是只按寬度縮小圖片,當圖片寬度大於750時就縮小到750 高度不用管 跟着寬度縮就行了
首先說一下思路,首先你要判斷圖片的寬度,這需要用到一個函數,個人比較喜歡用getimagesize()
其次是等比例綻放,需要用到imagecopyresized(當然還有其他函數)
注意:我這裡用到的是gd庫
實現:
寫一個函數或者類都行,我這裡就以面向過程的方式來寫,你可以整理一下
$file = ‘pic.jpg’; //原圖片文件
$maxWidth = 750;
$info = getimagesize($file); //取得一個圖片信息的數組,索引 0 包含圖像寬度的像素值,索引 1 包含圖像高度的像素值。索引 2 是圖像類型的標記
if($info[0] $maxWidth )
{
exit(‘圖片小於’.$maxWidth.’,不需要縮放’);
}
$im = imagecreatefromjpeg($file); //根據圖片的格式對應的不同的函數,在此不多贅述。
$rate = $maxWidth/$info[0]; //計算綻放比例
$maxHeight = floor($info[1]*$rate); //計算出縮放後的高度
$des_im = imagecreatetruecolor($maxWidth,$maxHeight); //創建一個縮放的畫布
imagecopyresized($des_im,$im,0,0,0,0,$maxWidth,$maxHeight,$info[0],$info[1]); //縮放
imagejpeg($des_im,’thumb.jpg’); //輸出到thumb.jpg即為一個縮放後的文件
求php圖片縮放處理函數
?php
/**
* 圖片縮放
* @param string $url
* @param int $maxWidth
* @param int $maxHeight
* @return string
*/
function thumb($url, $maxWidth, $maxHeight, $info) {
$info = $imgInfo = getimagesize($url);
$width = $imgInfo[0];//獲取圖片寬度
$height = $imgInfo[1];//獲取圖片高度
$r = min($maxHeight/$height, $maxWidth/$width);
if($r = 1) { // 不用縮放
$maxHeight = $height;
$maxWidth = $width;
} elseif($r 1) { // 縮放
$maxHeight = $height * $r;
$maxWidth = $width * $r;
}
$temp_img = imagecreatetruecolor($maxWidth,$maxHeight); //創建畫布
$fun = str_replace(‘/’, ‘createfrom’, $imgInfo[‘mime’]);
$im = $fun($url);
imagecopyresized($temp_img,$im,0,0,0,0,$maxWidth,$maxHeight,$width,$height);
ob_start();
$fun = str_replace(‘/’, ”, $imgInfo[‘mime’]);
$fun($temp_img);
$imgstr = ob_get_contents();
ob_end_clean();
imagedestroy($im);
return $imgstr;
}
$imgUrl = $_GET[‘url’];
$info = array();
$string = thumb($imgUrl, 500, 500, $info);
$mimeArray = explode(“/”, $info[‘mime’]);
header(“Content-Type:image/{$mimeArray[1]}”);
echo $string;
以上代碼存為thumb.php,調用效果:
php圖片可以等比例的縮放嗎
可以。
等比例縮放的方法是:
1、載入選區–自由變換。如下圖:
2、按住shift+alt鍵,使用鼠標調整大小,這種情況下,選區會按照等比例的方法進行縮放的。
php實現圖片等比例縮放代碼
新建文件index.php,需要在統計目錄下有個圖片為q.jpg(可根據源碼進行更改圖片的名稱)
源代碼如下:
?php
$filename=”q.jpg”;
$per=0.3;
list($width,
$height)=getimagesize($filename);
$n_w=$width*$per;
$n_h=$height*$per;
$new=imagecreatetruecolor($n_w,
$n_h);
$img=imagecreatefromjpeg($filename);
//拷貝部分圖像並調整
imagecopyresized($new,
$img,0,
0,0,
0,$n_w,
$n_h,
$width,
$height);
//圖像輸出新圖片、另存為
imagejpeg($new,
“q1.jpg”);
imagedestroy($new);
imagedestroy($img);
?
使用瀏覽器運行過後,在index.php同級的目錄下會有個q1.jpg,這個圖片就是等比例縮放後的圖片,路徑可以自己在源代碼裏面更改,放在自己的項目當中去或寫個方法也行
以上所述上就是本文的全部內容了,希望對大家學習php語言能夠有所幫助。
原創文章,作者:WMAY,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/135235.html