PHP GD是一個非常強大的圖像處理庫,它可以幫助我們輕松地編輯圖片和圖像。令人驚訝的是,GD庫已經(jīng)包括在PHP中了,所以您不需要安裝額外的庫。在本文中,我們將探討一些關(guān)于PHP GD的基礎(chǔ)知識和如何使用它來處理圖片。以下是一些例子:
1. 根據(jù)用戶上傳的圖片,創(chuàng)建一個具有固定尺寸的縮略圖:
<?php $filename = "original_image.jpg"; list($width, $height) = getimagesize($filename); $new_width = 100; $new_height = 100; $thumb = imagecreatetruecolor($new_width, $new_height); $source = imagecreatefromjpeg($filename); imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagejpeg($thumb, "thumbnail_image.jpg"); ?>
2. 通過圖片的文件名在畫布上插入水印:
<?php $filename = "original_image.jpg"; $watermark = "watermark.png"; list($width, $height) = getimagesize($filename); $image = imagecreatefromjpeg($filename); $stamp = imagecreatefrompng($watermark); $watermark_width = imagesx($stamp); $watermark_height = imagesy($stamp); $x_position = ($width - $watermark_width) / 2; $y_position = ($height - $watermark_height) / 2; imagecopy($image, $stamp, $x_position, $y_position, 0, 0, $watermark_width, $watermark_height); imagejpeg($image, "watermarked_image.jpg"); ?>
3. 根據(jù)用戶的選擇,將一張圖片旋轉(zhuǎn)90度或者水平翻轉(zhuǎn):
<?php $filename = "original_image.jpg"; $rotation = $_POST['rotation']; $flip = $_POST['flip']; $image = imagecreatefromjpeg($filename); if ($rotation == "90") { $image = imagerotate($image, 90, 0); } elseif ($flip == "horizontal") { $image = imageflip($image, IMG_FLIP_HORIZONTAL); } elseif ($flip == "vertical") { $image = imageflip($image, IMG_FLIP_VERTICAL); } imagejpeg($image, "modified_image.jpg"); ?>
這些例子并沒有涵蓋PHP GD的全部功能,但是您可以在這些例子中了解到一些基礎(chǔ)知識。如果您希望了解更多關(guān)于PHP GD的內(nèi)容,請參閱官方文檔。希望這篇文章對初學(xué)者有所幫助!