Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธาสร้างภาพสีจริง (True Color) ใหม่ใน PHP ด้วย imagecreatetruecolor()

imagecreatetruecolor() เป็นฟังก์ชันในตัวของ PHP ที่ใช้เพื่อสร้างภาพสีจริง (true-color image) ใหม่ คืนค่าภาพว่างในขนาดที่กำหนด

รูปแบบการใช้งาน (Syntax)

resource imagecreatetruecolor($width, $height)

พารามิเตอร์

imagecreatetruecolor() รับพารามิเตอร์ 2 ตัว ได้แก่ $width และ $height

  • $width - พารามิเตอร์ $width ใช้ตั้งค่าความกว้างของภาพ

  • $height - พารามิเตอร์ $height ใช้ตั้งค่าความสูงของภาพ

ค่าที่คืนกลับ (Return Values)

imagecreatetruecolor() คืนค่าตัวระบุทรัพยากรภาพ (image resource identifier) เมื่อสำเร็จ หรือคืนค่า false เมื่อเกิดข้อผิดพลาด

ตัวอย่างที่ 1

<?php 
// ตั้งค่าจุดมุมของรูปหลายเหลี่ยม
$values = array(
    150, 50,  // จุดที่ 1 (x, y)
    50, 250,  // จุดที่ 2 (x, y)
    250, 250  // จุดที่ 3 (x, y)
);
// สร้างขนาดภาพหรือภาพว่าง
$image = imagecreatetruecolor(700, 350);
// ตั้งสีพื้นหลังของภาพ
$background_color = imagecolorallocate($image, 122, 122, 122);
// เติมพื้นหลังด้วยสีที่เลือกข้างต้น
imagefill($image, 0, 0, $background_color);
// จัดสรรสีสำหรับรูปหลายเหลี่ยม
$image_color = imagecolorallocate($image, 0, 255, 255);
// วาดรูปหลายเหลี่ยม
imagepolygon($image, $values, 3, $image_color);
// ส่งภาพไปยังเบราว์เซอร์
header('Content-type: image/png');
imagepng($image); 
?>

ผลลัพธ์

วิธาสร้างภาพสีจริง (True Color) ใหม่ใน PHP ด้วย imagecreatetruecolor()

ตัวอย่างที่ 2 - โค้ด PHP ด้านล่างจะสร้างสตรีมภาพ GD ใหม่

<?php 
header ('Content-Type: image/gif');
$img = @imagecreatetruecolor(550, 220) or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($img, 255, 255, 0);
imagestring($img, 10, 50, 50, 'A Simple PHP Example', $text_color);
imagepng($img);
imagedestroy($img); 
?>

ผลลัพธ์

วิธาสร้างภาพสีจริง (True Color) ใหม่ใน PHP ด้วย imagecreatetruecolor()