标签:
1 /** 2 * @method 图片等比缩放 3 * @param string $srcImage 源图片路径 4 * @param string $toFile 目标图片路径 5 * @param integer $maxWidth 最大宽 6 * @param integer $maxHeight 最大高 7 * @param integer $imgQuality 图片质量 8 * @return 9 */ 10 function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) 11 { 12 13 list($width, $height, $type, $attr) = getimagesize($srcImage); 14 if($width < $maxWidth || $height < $maxHeight) return ; 15 switch ($type) { 16 case 1: $img = imagecreatefromgif($srcImage); break; 17 case 2: $img = imagecreatefromjpeg($srcImage); break; 18 case 3: $img = imagecreatefrompng($srcImage); break; 19 } 20 $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例 21 22 if($scale < 1) { 23 $newWidth = floor($scale*$width); 24 $newHeight = floor($scale*$height); 25 26 $newImg = imagecreatetruecolor($newWidth, $newHeight); 27 28 //以下三行代码是解决图片缩放后背景变成黑色的。 29 $color=imagecolorallocate($newImg,255,255,255); //颜色 30 imagecolortransparent($newImg,$color); 31 imagefill($newImg,0,0,$color); 32 33 imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 34 $newName = ""; 35 $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile); 36 37 switch($type) { 38 case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality)) 39 return "$newName.gif"; break; 40 case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) 41 return "$newName.jpg"; break; 42 case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality)) 43 return "$newName.png"; break; 44 default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) 45 return "$newName.jpg"; break; 46 } 47 //imagedestroy() 释放与 image 关联的内存。image 是由图像创建函数返回的图像标识符,例如 imagecreatetruecolor()。 48 imagedestroy($newImg); 49 } 50 else { 51 $bgimg = imagecreatetruecolor($maxWidth, $maxHeight); 52 53 //以下三行代码是解决图片缩放后背景变成黑色的。 54 $color=imagecolorallocate($bgimg,255,255,255); //颜色 55 imagecolortransparent($bgimg,$color); 56 imagefill($bgimg,0,0,$color); 57 58 imagedestroy($img); 59 } 60 61 return false; 62 }
图片缩放背景色变黑参考:http://www.jb51.net/article/56262.htm 谢谢分享!
php 5.4以上
标签:
原文地址:http://www.cnblogs.com/cyun/p/4242279.html