php实现按指定大小等比缩放生成上传图片缩略图的方法

yipeiwu_com6年前PHP代码库

本文实例讲述了php实现按指定大小等比缩放生成上传图片缩略图的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
/**
 * *
 *等比缩放
 * @param unknown_type $srcImage   源图片路径
 * @param unknown_type $toFile     目标图片路径
 * @param unknown_type $maxWidth   最大宽
 * @param unknown_type $maxHeight  最大高
 * @param unknown_type $imgQuality 图片质量
 * @return unknown
 */
function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)
{
  
    list($width, $height, $type, $attr) = getimagesize($srcImage);
    if($width < $maxWidth  || $height < $maxHeight) return ;
    switch ($type) {
    case 1: $img = imagecreatefromgif($srcImage); break;
    case 2: $img = imagecreatefromjpeg($srcImage); break;
    case 3: $img = imagecreatefrompng($srcImage); break;
    }
    $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例
    
    if($scale < 1) {
    $newWidth = floor($scale*$width);
    $newHeight = floor($scale*$height);
    $newImg = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    $newName = "";
    $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);
 
    switch($type) {
        case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))
        return "$newName.gif"; break;
        case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
        return "$newName.jpg"; break;
        case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))
        return "$newName.png"; break;
        default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
        return "$newName.jpg"; break;
    }
    imagedestroy($newImg);
    }
    imagedestroy($img);
    return false;
}

希望本文所述对大家的PHP程序设计有所帮助。

相关文章

php后台程序与Javascript的两种交互方式

方法一:通过Cookie交互。 一共是三个文件,分别为:index.htm,action.php,main.htm 原理为前台页面main.htm和后台action.php通过页面框架...

作为程序员必知的16个最佳PHP库

作为程序员必知的16个最佳PHP库

PHP是一种功能强大的web站点脚本语言,通过PHP,web网站开发者可以更容易地创建动态的引人入胜的web页面。开发人员可以使用PHP代码与一些网站模板和框架来提升功能和特性。然而,编...

让PHP更快的提供文件下载的代码

但是, 这样做, 就没办法做一些统计, 权限检查, 等等的工作. 于是, 很多时候, 我们采用让PHP来做转发, 为用户提供文件下载. 复制代码 代码如下: <?php $file...

php addslashes 利用递归实现使用反斜线引用字符串

实现代码:复制代码 代码如下:<?phpfunction addslashes_deep($value){//史上最经典的递归,一行搞定return is_array($value...

PHP Ajax实现页面无刷新发表评论

大家都有在网站发表评论的经历,传统的发表过程无非是:发表->提交页面表单->等待刷新页面,这样在网络比较拥挤的时候,往往需要漫长的等待,今天介绍用PHP+Ajax实现页面无刷...