2016/11/04

Codeigniter image_helper

前言

今天介紹兩個縮圖的 helper,使用的套件是 ImageWorkshop,以下面這兩張圖片解說。

500x300

300x500

程式碼

application/contollers/Image.php
<?php

class Image extends CI_Controller
{
    public function index()
    {
        $this->load->helper('image_helper');

        $this->load->view('image');
    }
}
application/helpers/image_helper.php
<?php

use PHPImageWorkshop\ImageWorkshop;

if (!function_exists('fit_thumb')) {
    function fit_thumb($path, $width = 150, $height = 0)
    {
        if (!file_exists($path)) {
            return 'assets/imgs/file_not_exists.png';
        }

        if ($height == 0) {
            $height = $ratio = $width;
        } else {
            $ratio = ($width < $height) ? $height : $width;
        }

        $paths = pathinfo($path);
        $thumbName = "{$paths['filename']}_fit_{$width}x{$height}.{$paths['extension']}";
        $thumbPath = $paths['dirname'].'/thumb/';
        $fullThumbPath = $thumbPath.$thumbName;

        if (file_exists($fullThumbPath)) {
            return $fullThumbPath;
        }

        $layer = ImageWorkshop::initFromPath($path, true);
        $layer->resizeByLargestSideInPixel($ratio, true);

        $layer->cropInPixel($width, $height, 0, 0, 'MT');
        $layer->save($thumbPath, $thumbName);

        return $fullThumbPath;
    }
}

if (!function_exists('thumb')) {
    function thumb($path, $ratio = 150, $bySide = 'large')
    {
        if (!file_exists($path)) {
            return 'assets/imgs/file_not_exists.png';
        }

        $paths = pathinfo($path);

        switch ($bySide) {
            case 'large':
                $thumbName = "{$paths['filename']}_thumb_large_{$ratio}.{$paths['extension']}";
                break;
            case 'narrow':
                $thumbName = "{$paths['filename']}_thumb_narrow_{$ratio}.{$paths['extension']}";
                break;
        }

        $thumbPath = $paths['dirname'].'/thumb/';
        $fullThumbPath = $thumbPath.$thumbName;

        if (file_exists($fullThumbPath)) {
            return $fullThumbPath;
        }

        $layer = ImageWorkshop::initFromPath($path, true);

        switch ($bySide) {
            case 'large':
                $layer->resizeByLargestSideInPixel($ratio, true);
                break;
            case 'narrow':
                $layer->resizeByNarrowSideInPixel($ratio, true);
                break;
        }

        $layer->save($thumbPath, $thumbName);

        return $fullThumbPath;
    }
}

if (!function_exists('img_upload')) {
    function img_upload($path = '/', $image = '', $maxWidth = 3000)
    {
        $status = 'done';
        $message = '';
        $allows = ['jpeg', 'png', 'gif'];
        $file = $_FILES[$image];
        $fileName = $file['name'];
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        $newName = date('YmdHis').rand(1000, 9999).'.'.$ext;
        $map = function ($item) {
            return "image/{$item}";
        };

        try {
            if (empty($fileName)) {
                throw new Exception('請選擇檔案');
            }

            $type = $file['type'];
            $tmpName = $file['tmp_name'];

            if (!in_array($type, array_map($map, $allows))) {
                throw new Exception('檔案格式錯誤,僅接受'.implode(', ', $allows));
            }

            $layer = ImageWorkshop::initFromPath($tmpName, true);
            list($width, $height) = getimagesize($tmpName);

            if ($width > $maxWidth) {
                $layer->resizeInPixel($maxWidth, null, true);
            }

            $layer->save($path, $newName);
        } catch (Exception $e) {
            $status = 'fail';
            $message = $e->getMessage();
        }

        return [
            'status' => $status,
            'image' => $newName,
            'message' => $message,
        ];
    }
}

if (!function_exists('image_delete')) {
    function image_delete($path, $image)
    {
        $path = rtrim($path, '/').'/';
        @unlink($path.$image);
        $fileName = pathinfo($image, PATHINFO_FILENAME);
        $thumbPath = $path.'thumb/';
        $thumbs = directory_map($thumbPath);

        foreach ($thumbs as $thumb) {
            $body = explode('_', $thumb)[0];

            if ($body === $fileName) {
                @unlink($thumbPath.$thumb);
            }
        }
    }
}
application/views/image.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Helper</title>
</head>
<body>
    <h3>500x300</h3>
    <img src="<?php echo $landscape; ?>">
    <h3>300x500</h3>
    <img src="<?php echo $portrait; ?>">

    <h3>fit_thumb</h3>
    <img src="<?php echo fit_thumb($landscape, 150); ?>">
    <img src="<?php echo fit_thumb($landscape, 150, 200); ?>">
    <img src="<?php echo fit_thumb($portrait, 150); ?>">
    <img src="<?php echo fit_thumb($portrait, 200, 150); ?>">

    <h3>thumb</h3>
    <img src="<?php echo thumb($landscape, 150); ?>">
    <img src="<?php echo thumb($landscape, 150, 'narrow'); ?>">
    <img src="<?php echo thumb($portrait, 150); ?>">
    <img src="<?php echo thumb($portrait, 150, 'narrow'); ?>">
</body>
</html>

Demo

fit_thumb

fit_thumb 如果沒有帶入第三個參數便會擷取該圖形為正方形,如果有帶入的話便會照比例擷取。

500x300

fit_thumb($landscape, 150)

150x150

fit_thumb($landscape, 150, 200)

150x200

300x500

fit_thumb($portrait, 150)

150x150

fit_thumb($portrait, 200, 150)

200x150

thumb

thumb 功能會依照傳入的比例參數將圖片依照參數等比例縮放,第二個參數可以決定從寬邊還是窄邊做縮放

500x300

thumb($landscape, 150)

150x90

thumb($landscape, 150, 'narrow')

250x150

300x500

thumb($portrait, 150)

90x150

thumb($portrait, 150, 'narrow')

150x250

img_upload

img_upload 這個 function 可以將你上傳的圖片縮圖後存入,一般來說網頁會顧慮的是寬不要破壞,因此程式碼會以寬度為主來做縮圖。

沒有留言:

張貼留言