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

PHP 圖片等比縮放類 SimpleImage 完整使用指南

     編輯:PHP 相關知識

SimpleImage 是一個輕量級的 PHP 圖片處理類,支援等比例縮放、指定寬高縮放、百分比縮放等功能,適合快速開發圖片處理需求。

基本用法範例

1. 指定寬度等比縮放

<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(250);
$image->save('picture2.jpg');
?>

2. 指定高度等比縮放

<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToHeight(500);
$image->save('picture2.jpg');

// 可連續操作
$image->resizeToHeight(200);
$image->save('picture3.jpg');
?>

3. 按百分比縮放

<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->scale(50);  // 縮放至 50%
$image->save('picture2.jpg');
?>

4. 直接輸出到瀏覽器

<?php
header('Content-Type: image/jpeg');
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(150);
$image->output();
?>

進階應用:遠端圖片下載並處理

<?php
include("SimpleImage.php");

$url = "https://f3.v.veimg.cn/meadincms/1/2013/0703/20130703100937552.jpg";
$picfile = down($url);  // 下載遠端圖片

$res = new SimpleImage();
$res->load($picfile);
$tmpfile = tempfile().'.jpg';  // 建立暫存檔路徑
$width = '30';
$res->resizeToWidth($width);
$res->save($tmpfile);  // 儲存處理後圖片

// 注意:此處會產生 3 個檔案(原始下載檔、暫存檔、處理後檔案)
// 實際專案建議加入清理機制刪除暫存檔

/**
 * 遠端圖片下載函數
 */
function down($url) {
    $http = array();
    $header = "https://f3.v.veimg.cn";
    if ($header) {
        $http['header'] = $header;
    }
    $http['timeout'] = 50;
    $ctx = stream_context_create(array('http' => $http));
    $content = @file_get_contents($url, 0, $ctx);
    sleep(1);
    if (!$content) return false;
    
    $tmpfile = tempfile();
    file_put_contents($tmpfile, $content);
    return $tmpfile;
}

/**
 * 產生唯一暫存檔路徑
 */
function tempfile() {
    $path = dirname(__FILE__) . '/spider/' . date('Ymd') . '/' . date('His') . '-' . (int)(time() / 300);
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }
    do {
        $file = $path . '/' . dechex(mt_rand());
    } while (file_exists($file));
    touch($file);
    return $file;
}
?>

SimpleImage 類完整原始碼

來源:White Hat Web Design

<?php
/*
 * File: SimpleImage.php
 * Author: Simon Jarvis
 * Copyright: 2006 Simon Jarvis
 * License: GNU General Public License v2+
 */

class SimpleImage {
    var $image;
    var $image_type;

    function load($filename) {
        $image_info = getimagesize($filename);
        $this->image_type = $image_info[2];
        
        if ($this->image_type == IMAGETYPE_JPEG) {
            $this->image = @imagecreatefromjpeg($filename);
        } elseif ($this->image_type == IMAGETYPE_GIF) {
            $this->image = @imagecreatefromgif($filename);
        } elseif ($this->image_type == IMAGETYPE_PNG) {
            $this->image = @imagecreatefrompng($filename);
        }
        
        if (!$this->image) return false;
        return $this;
    }

    function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = null) {
        if ($image_type == IMAGETYPE_JPEG) {
            imagejpeg($this->image, $filename, $compression);
        } elseif ($image_type == IMAGETYPE_GIF) {
            imagegif($this->image, $filename);
        } elseif ($image_type == IMAGETYPE_PNG) {
            imagepng($this->image, $filename);
        }
        if ($permissions != null) {
            chmod($filename, $permissions);
        }
    }

    function output($image_type = IMAGETYPE_JPEG) {
        if ($image_type == IMAGETYPE_JPEG) {
            imagejpeg($this->image);
        } elseif ($image_type == IMAGETYPE_GIF) {
            imagegif($this->image);
        } elseif ($image_type == IMAGETYPE_PNG) {
            imagepng($this->image);
        }
    }

    function getWidth() { return imagesx($this->image); }
    function getHeight() { return imagesy($this->image); }

    function resizeToHeight($height) {
        $ratio = $height / $this->getHeight();
        $width = $this->getWidth() * $ratio;
        $this->resize($width, $height);
    }

    function resizeToWidth($width) {
        if ($this->getWidth() < $width) $width = $this->getWidth();
        $ratio = $width / $this->getWidth();
        $height = $this->getHeight() * $ratio;
        $this->resize($width, $height);
    }

    function scale($scale) {
        $width = $this->getWidth() * $scale / 100;
        $height = $this->getHeight() * $scale / 100;
        $this->resize($width, $height);
    }

    function resize($width, $height) {
        $new_image = imagecreatetruecolor($width, $height);
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }

    // 保留透明度的進階縮放(GIF/PNG)
    function resize2($width, $height) {
        $new_image = imagecreatetruecolor($width, $height);
        if ($this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG) {
            $current_transparent = imagecolortransparent($this->image);
            if ($current_transparent != -1) {
                $transparent_color = imagecolorsforindex($this->image, $current_transparent);
                $current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
                imagefill($new_image, 0, 0, $current_transparent);
                imagecolortransparent($new_image, $current_transparent);
            } elseif ($this->image_type == IMAGETYPE_PNG) {
                imagealphablending($new_image, false);
                $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
                imagefill($new_image, 0, 0, $color);
                imagesavealpha($new_image, true);
            }
        }
        imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
        $this->image = $new_image;
    }
}

使用建議

  • 處理大量圖片時建議搭配快取機制,避免重複處理相同圖片
  • 遠端圖片下載後記得清理暫存檔,防止磁碟空間耗盡
  • 輸出 PNG/GIF 透明圖片時可使用 resize2() 方法保留透明度
  • 生產環境建議加入錯誤處理與日誌記錄
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved