讀取 GIF 圖片,建立同尺寸畫布,逐像素複製並垂直翻轉(上下顛倒),輸出 JPEG 格式。
<?php
$image = "images/csdn.gif"; // 來源圖片
$imgstream = file_get_contents($image);
$im = imagecreatefromstring($imgstream);
$thumbw = imagesx($im); // 原圖寬
$thumbh = imagesy($im); // 原圖高
// 建立目標畫布(支援 GD2 TrueColor)
if (function_exists("imagecreatetruecolor")) {
$dim = imagecreatetruecolor($thumbw, $thumbh);
} else {
$dim = imagecreate($thumbw, $thumbh); // GD1 相容
}
// 垂直翻轉:逐像素複製
for ($x = 0; $x < $thumbw; $x++) {
for ($y = 0; $y < $thumbh; $y++) {
// 來源 ($x, $y) → 目標 ($x, $thumbh-$y-1)
imagecopyresized($dim, $im, $x, $thumbh-$y-1, $x, $y, 1, 1, 1, 1);
}
}
// 輸出 JPEG
header("Content-type: image/jpeg");
imagejpeg($dim);
// 釋放資源
imagedestroy($im);
imagedestroy($dim);
?>
| 函式 | 用途 |
|---|---|
imagecreatefromstring() | 從二進位字串建立 GD 影像資源(支援多種格式) |
imagesx()/imagesy() | 取得影像寬/高 |
imagecreatetruecolor() | 建立 24-bit TrueColor 畫布(GD2),品質優於 imagecreate() |
imagecopyresized() | 複製並縮放像素區塊,此處用 1x1 實現單像素複製 |
imagejpeg() | 輸出 JPEG 到瀏覽器或檔案 |
imagecopy() 搭配整行/整區塊複製,或直接呼叫 imageflip($im, IMG_FLIP_VERTICAL) (PHP 5.5+)。imagedestroy() 釋放記憶體。<?php
$im = imagecreatefromgif("images/csdn.gif");
imageflip($im, IMG_FLIP_VERTICAL); // 內建翻轉,極快
header("Content-Type: image/gif");
imagegif($im);
imagedestroy($im);
?>
逐像素操作雖能展示 GD 底層運作原理,但實務開發請善用內建函式 imageflip()、imagerotate()、imagescale() 等經優化的 C 層實作,獲得數量級的效能提升。