PHP Conference Japan 2024

imageflip

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageflip使用給定模式翻轉影像

說明

imageflip(GdImage $image, int $mode): bool

使用給定的 mode 翻轉 image 影像。

參數

image

一個 GdImage 物件,由影像建立函式之一返回,例如 imagecreatetruecolor()

mode

翻轉模式,可以是 IMG_FLIP_* 常數之一

常數 意義
IMG_FLIP_HORIZONTAL 水平翻轉影像。
IMG_FLIP_VERTICAL 垂直翻轉圖像。
IMG_FLIP_BOTH 水平和垂直翻轉圖像。

返回值

成功時返回 true,失敗時返回 false

更新日誌

版本 說明
8.0.0 image 現在需要一個 GdImage 實例;先前需要一個有效的 gd 資源

範例

範例 #1 垂直翻轉圖像

此範例使用 IMG_FLIP_VERTICAL 常數。

<?php
// 檔案
$filename = 'phplogo.png';

// 內容類型
header('Content-type: image/png');

// 載入
$im = imagecreatefrompng($filename);

// 垂直翻轉
imageflip($im, IMG_FLIP_VERTICAL);

// 輸出
imagejpeg($im);
imagedestroy($im);
?>

上述範例將輸出類似以下的內容

Output of example: Vertically flipped image

範例 #2 水平翻轉圖像

此範例使用 IMG_FLIP_HORIZONTAL 常數。

<?php
// 檔案
$filename = 'phplogo.png';

// 內容類型
header('Content-type: image/png');

// 載入
$im = imagecreatefrompng($filename);

// 水平翻轉
imageflip($im, IMG_FLIP_HORIZONTAL);

// 輸出
imagejpeg($im);
imagedestroy($im);
?>

上述範例將輸出類似以下的內容

Output of example: Horizontally flipped image

新增註釋

使用者貢獻的註釋 1 則註釋

Daniel Klein
8 年前
如果您使用的 PHP 版本低於 5.5,可以使用以下程式碼新增相同的功能。如果傳入錯誤的 $mode,它會靜默失敗。您可能需要針對這種情況新增自己的錯誤處理。

<?php
if (!function_exists('imageflip')) {
define('IMG_FLIP_HORIZONTAL', 0);
define('IMG_FLIP_VERTICAL', 1);
define('IMG_FLIP_BOTH', 2);

function
imageflip($image, $mode) {
switch (
$mode) {
case
IMG_FLIP_HORIZONTAL: {
$max_x = imagesx($image) - 1;
$half_x = $max_x / 2;
$sy = imagesy($image);
$temp_image = imageistruecolor($image)? imagecreatetruecolor(1, $sy): imagecreate(1, $sy);
for (
$x = 0; $x < $half_x; ++$x) {
imagecopy($temp_image, $image, 0, 0, $x, 0, 1, $sy);
imagecopy($image, $image, $x, 0, $max_x - $x, 0, 1, $sy);
imagecopy($image, $temp_image, $max_x - $x, 0, 0, 0, 1, $sy);
}
break;
}
case
IMG_FLIP_VERTICAL: {
$sx = imagesx($image);
$max_y = imagesy($image) - 1;
$half_y = $max_y / 2;
$temp_image = imageistruecolor($image)? imagecreatetruecolor($sx, 1): imagecreate($sx, 1);
for (
$y = 0; $y < $half_y; ++$y) {
imagecopy($temp_image, $image, 0, 0, 0, $y, $sx, 1);
imagecopy($image, $image, 0, $y, 0, $max_y - $y, $sx, 1);
imagecopy($image, $temp_image, 0, $max_y - $y, 0, 0, $sx, 1);
}
break;
}
case
IMG_FLIP_BOTH: {
$sx = imagesx($image);
$sy = imagesy($image);
$temp_image = imagerotate($image, 180, 0);
imagecopy($image, $temp_image, 0, 0, 0, 0, $sx, $sy);
break;
}
default: {
return;
}
}
imagedestroy($temp_image);
}
}
?>
To Top