您可以將此函式與 imagecreatefromstring() 結合使用,以最少的麻煩(無需寫入暫存檔案)複製 gd 資源。
<?php
function cloneGd($gd)
{
ob_start();
imagegd2($gd);
return imagecreatefromstring(ob_get_clean());
}
?>
(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)
imagegd2 — 將 GD2 影像輸出到瀏覽器或檔案
$image
,$file
= null
,$chunk_size
= 128,$mode
= IMG_GD2_RAW
將 GD2 影像輸出到指定的 file
。
image
一個 GdImage 物件,由其中一個影像建立函式返回,例如 imagecreatetruecolor()。
file
要儲存檔案的路徑或開啟的串流資源(此函式返回後會自動關閉)。如果未設定或為 null
,則會直接輸出原始影像串流。
chunk_size
區塊大小。
mode
範例 #1 輸出 GD2 影像
<?php
// 建立空白影像並新增一些文字
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
// 輸出影像
imagegd2($im);
// 釋放記憶體
imagedestroy($im);
?>
範例 #2 儲存 GD2 影像
<?php
// 建立空白影像並新增文字
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "一段簡單的文字字串", $text_color);
// 儲存 gd2 影像
// GD2 影像的檔案格式為 .gd2,詳見 http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');
// 釋放記憶體
imagedestroy($im);
?>
注意事項:
GD2 格式通常用於快速載入影像的部分內容。請注意,GD2 格式只能在相容 GD2 的應用程式中使用。
GD 和 GD2 影像格式是 libgd 的專有影像格式。它們已被視為*過時*,並且僅應用於開發和測試目的。
您可以將此函式與 imagecreatefromstring() 結合使用,以最少的麻煩(無需寫入暫存檔案)複製 gd 資源。
<?php
function cloneGd($gd)
{
ob_start();
imagegd2($gd);
return imagecreatefromstring(ob_get_clean());
}
?>
是的,gd2 檔案格式確實提高了影像建立的速度,因為資料設定的設計是 GD 函式的原生格式 - 也就是說,在處理之前,影像不必轉換為可用格式。
您可能會注意到,新的 gd2 格式比舊的 imagegd 函式建立的檔案小得多,尤其是在涉及大塊單一顏色的圖片時更是如此。您可能會發現此函式在儲存較大圖片建立腳本中使用的覆蓋圖片或背景圖片時最有用。
要讀取 ping 或 jpeg 圖片(.png / .jpg)並將 .gd2 版本儲存到伺服器...
$img = $_GET['img'];
if(file_exists($img))
{
$dim = getimagesize($img);
$cr = ($dim[2] < 4) ? ($dim[2] < 3) ? ($dim[2] < 2) ? NULL : imagecreatefromjpeg($img) : imagecreatefrompng($img) : Null;
if($cr !== NULL)
{
imagegd2($cr,substr($img,0,strrpos($img,'.')).'.gd2');
}
}
應該會使用副檔名 .gd2 儲存具有相同檔名和目錄的副本,然後可以使用 imagecreatefromgd2 或 imagecreatefromgd2part 輕鬆快速地讀取。