PHP重置JPG图片尺寸的函数

代码如下:

<?php
/**
 * 重置Jpg图片尺寸
 * 
 * @param string $path
 * @param string $filename 源文件名
 * @param int $maxwidth
 * @param int $maxheight
 * @param string $newname 新文件名
 */
function reSizeJpg($path, $filename, $maxwidth, $maxheight, $newname)
{
    $jpg = imagecreatefromjpeg($path.'/'.$filename);
    if ($jpg) {
        $width = imagesx($jpg);
        $height = imagesy($jpg);
    } else {
        return false;
    }
    
    if (($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)) {
        if ($maxwidth && $width > $maxwidth) {
            $widthratio = $maxwidth / $width;
            $resize_width = true;
        }
        if ($maxheight && $height > $maxheight) {
            $heightratio = $maxheight / $height;
            $resize_height = true;
        }
        if ($resize_width && $resize_height) {
            if ($widthratio < $heightratio) {
                $ratio = $widthratio;
            } else {
                $ratio = $heightratio;
            }
        } elseif ($resize_width) {
            $ratio = $widthratio;
        } elseif ($resize_height) {
            $ratio = $heightratio;
        }
        $newwidth = $width * $ratio;
        $newheight = $height * $ratio;
        if (function_exists("imagecopyresampled")) {
            $newim = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($newim, $jpg, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        } else {
            $newim = imagecreate($newwidth, $newheight);
            imagecopyresized($newim, $jpg, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        }
        imagejpeg($newim, $path.'/'.$newname);
        imagedestroy($newim);
    } else {
        imagejpeg($jpg, $path.'/'.$newname);
    }
    imagedestroy($jpg);
    return true;
}
?>

相关内容: