php批量縮放圖片的代碼[ini參數控制]

來源:互聯網
上載者:User

首先使用一個ini檔案來設定要縮放的大小,其中為寬或高0的則為圖片放大或縮小,都為0則還是原大小,都不為0都拉抻成指定的大小。

注意:ini檔案使用php解釋時為注釋檔案,什麼也沒有輸出,這是為了安全起見而故意為之。而;則是ini檔案的注釋。

我設定的ini檔案例子如下:

複製代碼 代碼如下:<?php
/*
;Translate the image format using the original image size
[Translation]
width=0
height=0

;Stretch the image to the specified size
[Stretch]
width=800
height=600

;Zoom the image to the specified Width with height auto size
[AutoHeight]
width=740
height=0

;Zoom the image to the specified Height with width auto size
[AutoWidth]
width=0
height=380
*/
?>

下面是編寫的縮放圖片的php代碼,其中變數classes是一個數組,可以選擇任意多個ini檔案中指定的設定: 複製代碼 代碼如下:<?php
$oimg = "test.jpg";//Original image name
$classes = array('Translation','AutoHeight','AutoWidth','Stretch');//Give classes for the new creating images' size which are defined in the specified ini file
$suffix = 'jpg';//The new image's suffix
$inifile = 'image.ini.php';

$size = getimagesize($oimg);
$x = $size[0]/$size[1];
$name = explode('.',$oimg);

if(!file_exists($inifile)) die('Ini file does not exist!');
$cn = parse_ini_file($inifile,true);//Parse the class style image size from ini file
foreach($classes as $class){
foreach($cn as $k=>$v){
if($k==$class){
if($v['width'] && $v['height']){
$thumbWidth = $v['width'];
$thumbHeight = $v['height'];
}elseif($v['width']){
$thumbWidth = $v['width'];
$thumbHeight = round($thumbWidth/$x);
}elseif($v['height']){
$thumbHeight = $v['height'];
$thumbWidth = round($thumbHeight*$x);
}else{
$thumbWidth = $size[0];
$thumbHeight = $size[1];
}
break;
}
}
if(!isset($thumbHeight) && !isset($thumbWidth)) die('Ini file Settings error!');

$nimg = $name[0].'_'.$class.'.'.$suffix;//New image file name
$source = imagecreatefromjpeg($oimg);
$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($thumb,$source,0,0,0,0,$thumbWidth,$thumbHeight,$size[0],$size[1]);

if($suffix=='jpg') $method = 'imagejpeg';
else $method='image'.$suffix;
$method($thumb, $nimg);
imagedestroy($thumb);//Release the image source
imagedestroy($source);
}
?>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.