PHP-GD庫開發手記

建立帶有alpha通道的背景

 
 
 
 
 
$png = imagecreatetruecolor(800, 600);imagesavealpha($png, true);$trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);imagefill($png, 0, 0, $trans_colour);

輸出圖像

根據不一樣的圖片格式,選擇不一樣的函數php

 
 
 
 
 
header("Content-type: image/png");imagepng($img);imagedestroy($img);

畫中文字體

用ttftext函數便可,若是不是UTF8的編碼,記得用iconv函數轉碼一次函數

 
 
 
 
 
imagettftext ( $img, 20, 0, 0, 20, imagecolorallocate ( $img, 255, 255, 255 ),'g:/msyhbd.ttf', '啊啊啊啊啊啊啊啊啊啊啊啊啊');

獲取長寬

 
 
 
 
 
imagesx($tx);imagesy($tx);

等比例縮放圖片,也能夠用於裁切

 
 
 
 
 
$tx=imagecreatefromjpeg("G:/test.jpg" );$scaletx=imagecreatetruecolor(450, 450); //意思表示將tx圖片的從0,0座標長sx,寬sy的區域,從新採樣改變大小複製到stx的0,0座標,長寬爲450的區域。imagecopyresampled($scaletx, $tx, 0, 0, 0, 0, 450, 450, imagesx($tx), imagesy($tx));
 
 
 
 
 
private function resizeImage($src, $dest, $thumbWidth) { ini_set('memory_limit', '2048M'); if (!file_exists($src)) { return; } $image = imagecreatefrompng($src); $srcWidth = imagesx($image); // 原始寬高 $srcHeight = imagesy($image); $thumbHeight = ($srcHeight / $srcWidth) * $thumbWidth; // 處理後的高 imagesavealpha($image, true);//這裏很重要; $new = imagecreatetruecolor($thumbWidth, $thumbHeight); imagealphablending($new, false);//這裏很重要,意思是不合並顏色,直接用$img圖像顏色替換,包括透明色; imagesavealpha($new, true);//這裏很重要,意思是不要丟了$thumb圖像的透明色; imagecopyresampled($new, $image, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight); imagepng($new, $dest); imagedestroy($new); }

實例代碼

 
 
 
 
 
$img = imagecreatetruecolor ( 720, 1280 ); imagesavealpha ( $img, true );//保留通道,否則不透明 $trans_colour = imagecolorallocatealpha ( $img, 33, 0, 0, 33 ); imagefill ( $img, 0, 0, $trans_colour ); $tx = imagecreatefromjpeg ( "G:/Lotus.jpg" ); // 設置頭像居中 $width = 450; $height = 450; $w = imagesx ( $tx ); $h = imagesy ( $tx ); // 原圖尺寸小於縮略圖尺寸則不進行縮略 if ($w > $width || $h > $height) { // 計算縮放比例,選擇優先讓小的邊放大到指定等比寬度,大的邊隨意,爲了充滿屏幕 $scale = max ( $width / $w, $height / $h ); $width = $w * $scale; $height = $h * $scale; } //縮放 $scaletx = imagecreatetruecolor ( $width, $height ); imagecopyresampled ( $scaletx, $tx, 0, 0, 0, 0, $width, $height, $w, $h ); // 計算居中位置 $cx = (720 - $width) / 2; $cy = (1280 - $height) / 2 - 170; //覆蓋 imagecopy ( $img, $scaletx, $cx, $cy, 0, 0, $width, $height ); $bg = imagecreatefrompng ( "G:/test.png" ); imagesavealpha ( $bg, true ); imagecopy ( $img, $bg, 0, 0, 0, 0, imagesx ( $bg ), imagesy ( $bg ) ); // 寫名字 $name = '李昕'; $name_len = mb_strlen ( $name, 'utf8' );// 計算名字長度 $name_y =510-(45*$name_len/2);//居中 for($i = 0; $i < $name_len; $i ++) { imagettftext ( $img, 30, 0, 630, $name_y, imagecolorallocate ( $img, 255, 255, 255 ), 'msyhbd.ttf', mb_substr ( $name, $i, 1,'utf-8' )); $name_y += 45; } //寫編號 $vcode='01002'; imagettftext ( $img, 20, 0, 560, 1050, imagecolorallocate ( $img, 232, 255, 0 ), 'msyhbd.ttf', $vcode); header ( "content-type: image/jpg" ); imagejpeg ( $img, null, 100 );

相關文章
相關標籤/搜索