首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP GD 庫等比例縮圖生成與儲存完整類

     編輯:PHP 綜合知識

封裝 thumbnail() 與 imageToFile() 兩個函式,支援 JPEG/PNG/GIF/BMP,自動偵測型別並維持長寬比。

<?php
function thumbnail($inputFile, $maxSize = 100) {
    $info = getimagesize($inputFile);
    $type = isset($info['type']) ? $info['type'] : $info[2];
    if (!(imagetypes() & $type)) return false; // 不支援格式
    $w = isset($info['width']) ? $info['width'] : $info[0];
    $h = isset($info['height']) ? $info['height'] : $info[1];
    if ($w <= $maxSize && $h <= $maxSize) return imagecreatefromstring(file_get_contents($inputFile));
    $wRatio = $maxSize / $w; $hRatio = $maxSize / $h;
    if ($wRatio * $h < $maxSize) { $tW = $maxSize; $tH = ceil($wRatio * $h); }
    else { $tH = $maxSize; $tW = ceil($hRatio * $w); }
    $src = imagecreatefromstring(file_get_contents($inputFile));
    $thumb = imagecreatetruecolor($tW, $tH);
    imagecopyresampled($thumb, $src, 0,0,0,0, $tW,$tH, $w,$h);
    imagedestroy($src);
    return $thumb;
}

function imageToFile($im, $fileName, $quality = 80) {
    if (!$im || file_exists($fileName)) return false;
    $ext = strtolower(substr($fileName, strrpos($fileName, '.')));
    switch ($ext) {
        case '.gif':  return imagegif($im, $fileName);
        case '.jpg': case '.jpeg': return imagejpeg($im, $fileName, $quality);
        case '.png':  return imagepng($im, $fileName);
        case '.bmp':  return imagewbmp($im, $fileName);
        default: return false;
    }
}

// 使用範例
$im = thumbnail('temp.jpg', 100);
imageToFile($im, 'temp-thumbnail.jpg');
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved