PHP Conference Japan 2024

Imagick::cropThumbnailImage

(PECL imagick 2,PECL imagick 3)

Imagick::cropThumbnailImage建立裁剪縮圖

說明

public Imagick::cropThumbnailImage(int $width, int $height, bool $legacy = false): bool

藉由先放大或縮小影像,然後從中心裁剪指定的區域來建立固定大小的縮圖。

參數

width

縮圖的寬度

height

縮圖的高度

傳回值

成功時傳回 true

錯誤/例外

發生錯誤時擲回 ImagickException。

新增筆記

使用者提供的筆記 3 個筆記

6
martijn at elicit dot nl
14 年前
我認為此函式無法如預期運作,已針對 imagemagick 版本 6.3.7 進行測試

如上所述,此函式會傳回具有固定高度和可變寬度的影像。以下是一個修正方法,可以傳回具有已定義尺寸的裁剪縮圖,而不會有尺寸變化。

<?php
// 定義寬螢幕尺寸
$width = 160;
$height = 90;

// 載入影像
$i = new Imagick("您的影像檔案");
// 取得目前影像尺寸
$geo = $i->getImageGeometry();

// 裁剪影像
if(($geo['width']/$width) < ($geo['height']/$height))
{
$i->cropImage($geo['width'], floor($height*$geo['width']/$width), 0, (($geo['height']-($height*$geo['width']/$width))/2));
}
else
{
$i->cropImage(ceil($width*$geo['height']/$height), $geo['height'], (($geo['width']-($width*$geo['height']/$height))/2), 0);
}
// 縮圖影像
$i->ThumbnailImage($width,$height,true);

// 儲存或顯示或任何影像
$i->setImageFormat("png");
header("Content-Type: image/png");
exit(
$i);
?>
4
sonsandsons at gmail dot com
13 年前
值得注意的是,如果您使用 .gif 影像格式,使用 cropThumbnailImage 可能會出現不想要的結果。如果您使用 .gif,您需要透過移除畫布來輔助此函式。

<?php

// 實例化 image magick 類別
$image = new Imagick($image_path);

// 裁剪並調整影像大小
$image->cropThumbnailImage(100,100);

// 移除畫布
$image->setImagePage(0, 0, 0, 0);

?>
2
benford at bluhelix dot com
15 年前
我在此網站上找到一個相關的文章,其中包含完整的示範程式碼
http://valokuva.org/?p=8

範例程式碼如下所示
<?php
/* 讀取影像 */
$im = new imagick( "test.png" );
/* 建立縮圖 */
$im->cropThumbnailImage( 80, 80 );
/* 寫入檔案 */
$im->writeImage( "th_80x80_test.png" );
?>

這是 cropImage 方法的特殊化。在高階層次中,此方法會建立給定影像的縮圖,縮圖的大小為 ($width, $height)。

如果縮圖不符合來源影像的縱橫比,則這是要使用的方法。縮圖將會擷取來源影像較短邊的整個影像(例如,橫向影像的垂直大小)。然後將縮圖縮小以符合您的目標高度,同時保留縱橫比。不符合目標 $width 的額外水平空間將會左右均勻裁剪掉。

因此,縮圖通常是來源影像的良好呈現。
To Top