PHP 圖像居中裁剪函數

圖像居中裁減的大體思路:瀏覽器

1.首先將圖像進行縮放,使得縮放後的圖像可以剛好覆蓋裁減區域。(imagecopyresampled — 重採樣拷貝部分圖像並調整大小函數

2.將縮放後的圖像放置在裁減區域中間。(imagecopy — 拷貝圖像的一部分spa

3.裁減圖像並保存。(imagejpeg | imagepng | imagegif — 輸出圖象到瀏覽器或文件code

==================縮放裁剪函數====================blog

/**
 * 居中裁剪圖片
 * @param string $source [原圖路徑]
 * @param int $width [設置寬度]
 * @param int $height [設置高度]
 * @param string $target [目標路徑]
 * @return bool [裁剪結果]
 */
function image_center_crop($source, $width, $height, $target)
{
    if (!file_exists($source)) return false;
    /* 根據類型載入圖像 */
    switch (exif_imagetype($source)) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($source);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($source);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($source);
            break;
    }
    if (!isset($image)) return false;
    /* 獲取圖像尺寸信息 */
    $target_w = $width;
    $target_h = $height;
    $source_w = imagesx($image);
    $source_h = imagesy($image);
    /* 計算裁剪寬度和高度 */
    $judge = (($source_w / $source_h) > ($target_w / $target_h));
    $resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
    $resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
    $start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
    $start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
    /* 繪製居中縮放圖像 */
    $resize_img = imagecreatetruecolor($resize_w, $resize_h);
    imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
    $target_img = imagecreatetruecolor($target_w, $target_h);
    imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
    /* 將圖片保存至文件 */
    if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
    switch (exif_imagetype($source)) {
        case IMAGETYPE_JPEG:
            imagejpeg($target_img, $target);
            break;
        case IMAGETYPE_PNG:
            imagepng($target_img, $target);
            break;
        case IMAGETYPE_GIF:
            imagegif($target_img, $target);
            break;
    }
    return boolval(file_exists($target));
}

==================函數使用方式====================圖片

// 原始圖片的路徑
$source = '../source/img/middle.jpg';
$width = 480; // 裁剪後的寬度
$height = 480;// 裁剪後的高度
// 裁剪後的圖片存放目錄
$target = '../source/temp/resize.jpg';
// 裁剪後保存到目標文件夾
if (image_center_crop($source, $width, $height, $target)) {
    echo "<img src='$target'>";
}

==================圖片裁剪效果====================get

                                               原圖:1440*900string

                                    裁剪後:480*120it

                       裁剪後:480*480io

                 裁剪後:480*720

相關文章
相關標籤/搜索