Kotchasan Framework Documentation

Kotchasan Framework Documentation

คลาส Image - การประมวลผลรูปภาพ

TH 05 Feb 2026 07:40

คลาส Image - การประมวลผลรูปภาพ

คลาส Image เป็นยูทิลิตี้สำหรับการโหลด ประมวลผล และบันทึกรูปภาพ รองรับหลายรูปแบบ และมีฟังก์ชันสำหรับการครอป ปรับขนาด พลิก และเพิ่มลายน้ำ

Namespace

Kotchasan\Image

ภาพรวม

Image class ให้บริการ:

  • โหลดรูปภาพจากไฟล์หรือ Base64
  • ครอปและปรับขนาดรูปภาพ
  • พลิกรูปภาพ (แนวน ​​อนและแนวตั้ง)
  • เพิ่มลายน้ำข้อความ
  • ปรับทิศทางรูปภาพตาม EXIF data
  • รองรับ JPG, PNG, GIF, WEBP

Static Properties

public static $quality = 75;                           // คุณภาพรูปภาพ (0-100)
public static $backgroundColor = [255, 255, 255];       // สีพื้นหลังเริ่มต้น (RGB สีขาว)
public static $fontPath = __DIR__.'/fonts/leelawad.ttf'; // ฟอนต์สำหรับลายน้ำภาษาไทย

API Reference

loadImageResource()

โหลดรูปภาพจากไฟล์และสร้าง image resource

public static function loadImageResource($source)

Parameters:

  • $source (string) - พาธไฟล์รูปภาพต้นทาง

Returns: Mixed - Image resource (GD library resource)

Throws: \RuntimeException - ถ้าไฟล์ไม่ถูกต้องหรือไม่รองรับ

Example:

use Kotchasan\Image;

try {
    $imageResource = Image::loadImageResource('/path/to/image.jpg');

    // ใช้งาน image resource
    $width = imagesx($imageResource);
    $height = imagesy($imageResource);

    echo "ขนาด: {$width}x{$height}";

    imagedestroy($imageResource);
} catch (\RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

loadImageFromBase64()

โหลดรูปภาพจาก Base64 string

public static function loadImageFromBase64($base64_string, $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'])

Parameters:

  • $base64_string (string) - Base64 encoded string ของรูปภาพ
  • $allowedExtensions (array) - รายการนามสกุลที่อนุญาต

Returns: array|false - Array ที่มี resource, mime, extension หรือ false ถ้าล้มเหลว

Example:

use Kotchasan\Image;

$base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUg...';

$result = Image::loadImageFromBase64($base64);

if ($result) {
    echo "MIME Type: " . $result['mime'];
    echo "Extension: " . $result['extension'];

    // บันทึกเป็นไฟล์
    Image::saveImageResource($result['resource'], '/path/to/output.png');

    imagedestroy($result['resource']);
} else {
    echo "ไม่สามารถโหลดรูปภาพจาก Base64 ได้";
}

// จำกัดเฉพาะ JPG และ PNG
$result = Image::loadImageFromBase64($base64, ['jpg', 'jpeg', 'png']);

processImageResource()

ประมวลผล image resource โดยปรับขนาดหรือครอปตามขนาดที่กำหนด

public static function processImageResource($o_im, $thumbwidth, $thumbheight = 0, $watermark = '', $fit = false)

Parameters:

  • $o_im (Mixed) - Image resource ต้นทาง
  • $thumbwidth (int) - ความกว้างที่ต้องการ
  • $thumbheight (int) - ความสูงที่ต้องการ (0 = คงสัดส่วน)
  • $watermark (string) - ข้อความลายน้ำ (optional)
  • $fit (bool) - true = fit รูปให้พอดีกรอบ, false = crop ให้เต็มกรอบ

Returns: Mixed - Image resource ที่ประมวลผลแล้ว

Example:

use Kotchasan\Image;

$sourceImage = Image::loadImageResource('/path/to/photo.jpg');

// ปรับขนาดคงสัดส่วน (กว้างสูงสุด 800px)
$resized = Image::processImageResource($sourceImage, 800);

// ครอปเป็น 300x300
$cropped = Image::processImageResource($sourceImage, 300, 300);

// Fit เป็น 400x300 พร้อมลายน้ำ
$fitted = Image::processImageResource($sourceImage, 400, 300, 'Copyright 2024', true);

// บันทึก
Image::saveImageResource($fitted, '/path/to/output.jpg');

imagedestroy($sourceImage);
imagedestroy($fitted);

saveImageResource()

บันทึก image resource เป็นไฟล์

public static function saveImageResource($imageResource, $target)

Parameters:

  • $imageResource (Mixed) - Image resource ที่จะบันทึก
  • $target (string) - พาธไฟล์ปลายทาง

Returns: bool - สำเร็จหรือไม่

Throws: \RuntimeException - ถ้านามสกุลไม่รองรับหรือบันทึกล้มเหลว

Example:

use Kotchasan\Image;

$image = Image::loadImageResource('/path/to/source.jpg');

// บันทึกเป็น JPG
Image::saveImageResource($image, '/path/to/output.jpg');

// บันทึกเป็น PNG
Image::saveImageResource($image, '/path/to/output.png');

// บันทึกเป็น WEBP
Image::saveImageResource($image, '/path/to/output.webp');

imagedestroy($image);

crop()

ครอปและปรับขนาดรูปภาพ

public static function crop($source, $target, $thumbwidth, $thumbheight, $watermark = '', $fit = false)

Parameters:

  • $source (string) - พาธไฟล์ต้นทาง
  • $target (string) - พาธบันทึกไฟล์
  • $thumbwidth (int) - ความกว้างที่ต้องการ
  • $thumbheight (int) - ความสูงที่ต้องการ
  • $watermark (string) - ข้อความลายน้ำ (optional)
  • $fit (bool) - true = fit, false = crop

Returns: bool - สำเร็จหรือไม่

Example:

use Kotchasan\Image;

// ครอปเป็น 200x200 (crop mode)
Image::crop('/path/to/photo.jpg', '/path/to/thumb.jpg', 200, 200);

// Fit เป็น 300x200 พร้อมลายน้ำ
Image::crop('/path/to/photo.jpg', '/path/to/fitted.jpg', 300, 200, 'My Photo', true);

// สร้าง thumbnail
Image::crop('/uploads/profile.jpg', '/uploads/thumb_profile.jpg', 150, 150);

resize()

ปรับขนาดรูปภาพและบันทึก

public static function resize($source, $target, $name, $width = 0, $watermark = '')

Parameters:

  • $source (string) - พาธไฟล์ต้นทาง
  • $target (string) - ไดเรกทอรีปลายทาง
  • $name (string) - ชื่อไฟล์ผลลัพธ์
  • $width (int) - ความกว้างที่ต้องการ (0 = ใช้ขนาดเดิม)
  • $watermark (string) - ข้อความลายน้ำ (optional)

Returns: array|false - ข้อมูลรูปภาพหรือ false

Example:

use Kotchasan\Image;

$result = Image::resize(
    '/uploads/original.jpg',
    '/uploads/',
    'resized.jpg',
    800,
    'Copyright 2024'
);

if ($result) {
    echo "ชื่อไฟล์: " . $result['name'];
    echo "ขนาด: {$result['width']}x{$result['height']}";
    echo "MIME: " . $result['mime'];
}

flip()

พลิกรูปภาพแนวนอน

public static function flip($imgsrc)

Parameters:

  • $imgsrc (Mixed) - Image resource ต้นทาง

Returns: Mixed - Image resource ที่พลิกแล้ว

Example:

use Kotchasan\Image;

$image = Image::loadImageResource('/path/to/photo.jpg');
$flipped = Image::flip($image);

Image::saveImageResource($flipped, '/path/to/flipped.jpg');

imagedestroy($image);
imagedestroy($flipped);

flipVertical()

พลิกรูปภาพแนวตั้ง

public static function flipVertical($imgsrc)

Parameters:

  • $imgsrc (Mixed) - Image resource ต้นทาง

Returns: Mixed - Image resource ที่พลิกแล้ว

Example:

use Kotchasan\Image;

$image = Image::loadImageResource('/path/to/photo.jpg');
$flipped = Image::flipVertical($image);

Image::saveImageResource($flipped, '/path/to/flipped_vertical.jpg');

imagedestroy($image);
imagedestroy($flipped);

info()

ดึงข้อมูลรูปภาพ เช่น ความกว้าง ความสูง และ MIME type

public static function info($source)

Parameters:

  • $source (string) - พาธไฟล์รูปภาพ

Returns: array - ข้อมูลรูปภาพ (width, height, mime)

Throws: \RuntimeException - ถ้าไม่สามารถอ่านข้อมูลได้

Example:

use Kotchasan\Image;

try {
    $info = Image::info('/path/to/photo.jpg');

    echo "ความกว้าง: " . $info['width'];
    echo "ความสูง: " . $info['height'];
    echo "MIME Type: " . $info['mime'];

    // ตรวจสอบขนาด
    if ($info['width'] > 2000 || $info['height'] > 2000) {
        echo "รูปภาพมีขนาดใหญ่เกินไป";
    }
} catch (\RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

orient()

ปรับทิศทางรูปภาพตาม EXIF data

public static function orient($source)

Parameters:

  • $source (string) - พาธไฟล์รูปภาพ JPEG

Returns: Mixed - Image resource ที่ปรับทิศทางแล้ว

Throws: \RuntimeException - ถ้าสร้าง resource ล้มเหลว

Example:

use Kotchasan\Image;

// ปรับทิศทางรูปที่ถ่ายจากมือถือ
$image = Image::orient('/path/to/phone_photo.jpg');

Image::saveImageResource($image, '/path/to/corrected.jpg');

imagedestroy($image);

watermarkText()

เพิ่มลายน้ำข้อความลงในรูปภาพ

public static function watermarkText($imgsrc, $text, $pos = 'bottom-right', $color = 'CCCCCC', $font_size = 20, $opacity = 50)

Parameters:

  • $imgsrc (Mixed) - Image resource ต้นทาง
  • $text (string) - ข้อความลายน้ำ
  • $pos (string) - ตำแหน่ง: 'center', 'bottom-right', 'bottom-left', 'top-right', 'top-left'
  • $color (string) - สีในรูปแบบ hex (เช่น 'CCCCCC')
  • $font_size (int) - ขนาดฟอนต์
  • $opacity (int) - ความทึบแสง (0-100)

Returns: Mixed - Image resource ที่เพิ่มลายน้ำแล้ว

Throws: \RuntimeException - ถ้าไม่พบไฟล์ฟอนต์

Example:

use Kotchasan\Image;

$image = Image::loadImageResource('/path/to/photo.jpg');

// ลายน้ำมุมขวาล่าง
Image::watermarkText($image, 'Copyright 2024');

// ลายน้ำกึ่งกลาง สีขาว ทึบแสง 70%
Image::watermarkText($image, 'DRAFT', 'center', 'FFFFFF', 40, 70);

// ลายน้ำภาษาไทย
Image::watermarkText($image, 'ลิขสิทธิ์ 2567', 'bottom-right', '000000', 18, 60);

Image::saveImageResource($image, '/path/to/watermarked.jpg');

imagedestroy($image);

setQuality()

ตั้งค่าคุณภาพรูปภาพสำหรับ JPEG และ WEBP

public static function setQuality($quality)

Parameters:

  • $quality (int) - ระดับคุณภาพ (0-100)

Returns: void

Example:

use Kotchasan\Image;

// ตั้งค่าคุณภาพสูง
Image::setQuality(90);

$image = Image::loadImageResource('/path/to/photo.jpg');
Image::saveImageResource($image, '/path/to/high_quality.jpg');

// ตั้งค่าคุณภาพต่ำ (ลดขนาดไฟล์)
Image::setQuality(60);
Image::saveImageResource($image, '/path/to/low_quality.jpg');

imagedestroy($image);

ตัวอย่างการใช้งานจริง

1. ระบบอัปโหลดรูปโปรไฟล์

use Kotchasan\Image;
use Kotchasan\File;

class ProfileImageUploader
{
    public function upload($uploadedFile, $userId)
    {
        $uploadDir = ROOT_PATH . "uploads/profiles/{$userId}/";
        File::makeDirectory($uploadDir);

        $tempPath = $uploadedFile->getStream()->getMetadata('uri');
        $extension = File::ext($uploadedFile->getClientFilename());

        // ตรวจสอบว่าเป็นรูปภาพ
        try {
            $info = Image::info($tempPath);
        } catch (\RuntimeException $e) {
            return ['error' => 'ไฟล์ไม่ใช่รูปภาพ'];
        }

        // ตรวจสอบขนาด
        if ($info['width'] < 200 || $info['height'] < 200) {
            return ['error' => 'รูปภาพมีขนาดเล็กเกินไป (ต้องการอย่างน้อย 200x200)'];
        }

        $filename = 'profile_' . time() . '.jpg';

        // สร้างรูปภาพหลัก (800x800)
        Image::crop($tempPath, $uploadDir . $filename, 800, 800);

        // สร้าง thumbnail (150x150)
        Image::crop($tempPath, $uploadDir . 'thumb_' . $filename, 150, 150);

        return [
            'success' => true,
            'filename' => $filename,
            'url' => "/uploads/profiles/{$userId}/{$filename}"
        ];
    }
}

2. ระบบสร้าง Thumbnail อัตโนมัติ

class ThumbnailGenerator
{
    private $sizes = [
        'small' => 150,
        'medium' => 300,
        'large' => 600
    ];

    public function generateThumbnails($sourcePath, $outputDir)
    {
        File::makeDirectory($outputDir);

        $results = [];
        $baseName = pathinfo($sourcePath, PATHINFO_FILENAME);

        foreach ($this->sizes as $sizeName => $width) {
            $targetFile = "{$baseName}_{$sizeName}.jpg";
            $targetPath = $outputDir . $targetFile;

            $result = Image::resize($sourcePath, $outputDir, $targetFile, $width);

            if ($result) {
                $results[$sizeName] = [
                    'filename' => $result['name'],
                    'width' => $result['width'],
                    'height' => $result['height']
                ];
            }
        }

        return $results;
    }
}

3. ระบบสร้างรูปภาพสินค้า

class ProductImageProcessor
{
    public function process($uploadedFile, $productId)
    {
        $productDir = ROOT_PATH . "products/{$productId}/";
        File::makeDirectory($productDir);

        $tempPath = $uploadedFile->getStream()->getMetadata('uri');

        // ตั้งค่าคุณภาพสูง
        Image::setQuality(85);

        // ปรับทิศทาง (กรณีถ่ายจากมือถือ)
        $image = Image::orient($tempPath);

        // สร้างรูปภาพหลัก 1200x1200 พร้อมลายน้ำ
        $mainImage = Image::processImageResource($image, 1200, 1200, 'MyShop.com');
        Image::saveImageResource($mainImage, $productDir . 'main.jpg');

        // สร้าง thumbnail 300x300
        $thumb = Image::processImageResource($image, 300, 300);
        Image::saveImageResource($thumb, $productDir . 'thumb.jpg');

        // สร้าง gallery (fit mode) 800x600
        $gallery = Image::processImageResource($image, 800, 600, '', true);
        Image::saveImageResource($gallery, $productDir . 'gallery.jpg');

        imagedestroy($image);
        imagedestroy($mainImage);
        imagedestroy($thumb);
        imagedestroy($gallery);

        return [
            'main' => "products/{$productId}/main.jpg",
            'thumb' => "products/{$productId}/thumb.jpg",
            'gallery' => "products/{$productId}/gallery.jpg"
        ];
    }
}

4. ระบบประมวลผลรูปภาพจาก Base64

class Base64ImageHandler
{
    public function saveFromBase64($base64String, $outputPath)
    {
        $result = Image::loadImageFromBase64($base64String, ['jpg', 'png']);

        if (!$result) {
            return ['error' => 'Base64 ไม่ถูกต้องหรือประเภทไฟล์ไม่รองรับ'];
        }

        // บันทึกรูปต้นฉบับ
        $originalPath = $outputPath . 'original.' . $result['extension'];
        Image::saveImageResource($result['resource'], $originalPath);

        // สร้าง thumbnail
        $thumb = Image::processImageResource($result['resource'], 200, 200);
        Image::saveImageResource($thumb, $outputPath . 'thumb.jpg');

        imagedestroy($result['resource']);
        imagedestroy($thumb);

        return [
            'success' => true,
            'original' => $originalPath,
            'thumb' => $outputPath . 'thumb.jpg'
        ];
    }
}

Best Practices

1. ทำลาย Image Resource หลังใช้งาน

// ✅ Good
$image = Image::loadImageResource($source);
// ... ใช้งาน
imagedestroy($image);

// ❌ Bad - memory leak
$image = Image::loadImageResource($source);
// ... ใช้งานแล้วไม่ destroy

2. ตรวจสอบข้อมูลรูปภาพก่อนประมวลผล

// ✅ Good
try {
    $info = Image::info($source);

    if ($info['width'] > 5000 || $info['height'] > 5000) {
        throw new \Exception('รูปภาพมีขนาดใหญ่เกินไป');
    }

    Image::crop($source, $target, 800, 800);
} catch (\Exception $e) {
    // Handle error
}

3. ตั้งค่าคุณภาพตามวัตถุประสงค์

// ✅ Good
// สำหรับ thumbnail - ใช้คุณภาพต่ำ
Image::setQuality(70);
Image::resize($source, $thumbDir, 'thumb.jpg', 200);

// สำหรับรูปหลัก - ใช้คุณภาพสูง
Image::setQuality(90);
Image::resize($source, $mainDir, 'main.jpg', 1200);

4. ใช้ try-catch สำหรับ Operations ที่อาจล้มเหลว

// ✅ Good
try {
    $image = Image::loadImageResource($source);
    Image::saveImageResource($image, $target);
    imagedestroy($image);
} catch (\RuntimeException $e) {
    error_log("Image processing failed: " . $e->getMessage());
    return false;
}

ข้อควรระวัง

[!WARNING]
Memory Usage: การประมวลผลรูปภาพขนาดใหญ่ใช้ memory มาก ควรเพิ่ม memory_limit ในภาพขายใหญ่

[!IMPORTANT]
GD Library Required: ต้องมี PHP GD extension ติดตั้ง

[!NOTE]
EXIF Support: orient() ต้องการ EXIF extension สำหรับอ่านข้อมูล orientation

[!TIP]
Font Path: สำหรับลายน้ำภาษาไทย ต้องมีฟอนต์ที่ /fonts/leelawad.ttf

คลาสที่เกี่ยวข้อง

  • [File] - File และ directory management
  • [Files] - File upload collections

สรุป

Image class มี 11 เมธอดหลัก:

  1. loadImageResource() - โหลดรูปจากไฟล์
  2. loadImageFromBase64() - โหลดรูปจาก Base64
  3. processImageResource() - ประมวลผล resize/crop
  4. saveImageResource() - บันทึกเป็นไฟล์
  5. crop() - ครอปรูปภาพ
  6. resize() - ปรับขนาดรูปภาพ
  7. flip() - พลิกแนวนอน
  8. flipVertical() - พลิกแนวตั้ง
  9. info() - ดึงข้อมูลรูปภาพ
  10. orient() - ปรับทิศทางตาม EXIF
  11. watermarkText() - เพิ่มลายน้ำข้อความ
  12. setQuality() - ตั้งค่าคุณภาพ

เหมาะสำหรับ:

  • ระบบอัปโหลดรูปโปรไฟล์
  • ระบบจัดการรูปภาพสินค้า
  • สร้าง thumbnail อัตโนมัติ
  • ประมวลผลรูปภาพจาก Base64
  • เพิ่มลายน้ำลิขสิทธิ์