imagecolorclosestalpha()
ฟังก์ชั่น imagecolorclosestalpha () เป็นฟังก์ชั่น inbuilt ใน PHP ซึ่งใช้ในการรับดัชนี(index) สีของ colorclosest โดยใช้ค่าอัลฟาในภาพที่กำหนด ฟังก์ชั่นนี้จะคืนค่าดัชนี(index)ของสีในจานสีของภาพซึ่งใกล้เคียงกับค่า RGB และระดับอัลฟาที่ระบุมากที่สุด ค่าอัลฟ่าหมายถึงความโปร่งใสของภาพ
int imagecolorclosestalpha ( $image, $red, $green, $blue, $alpha )
พารามิเตอร์:ฟังก์ชั่นนี้จะรับห้าพารามิเตอร์ดังนี้:
- $ image:มันถูกส่งคืนโดยหนึ่งในฟังก์ชั่นการสร้างภาพเช่น imagecreatetruecolor() ซึ่งใช้เพื่อสร้างขนาดของภาพ
- $ red:พารามิเตอร์นี้ใช้เพื่อตั้งค่าองค์ประกอบสีแดง
- $ green:พารามิเตอร์นี้ใช้เพื่อตั้งค่าองค์ประกอบสีเขียว
- $ blue:พารามิเตอร์นี้ใช้เพื่อตั้งค่าองค์ประกอบสีฟ้า
- $ alpha:พารามิเตอร์นี้ใช้เพื่อตั้งค่าความโปร่งใสของภาพ ค่าของ $alpha อยู่ระหว่าง 0 ถึง 127 โดยที่ 0 หมายถึงทึบแสงสมบูรณ์ขณะที่ 127 แสดงถึงความโปร่งใสอย่างสมบูรณ์
ตัวอย่างโค้ด ดังนี้
<?php
// Convert an image into a palette-based image
$image = imagecreatefrompng(
'https://cdncontribute.geeksforgeeks.org/wp-content/uploads/col1.png');
imagetruecolortopalette($image, false, 255);
// Find closest color in image
$output = imagecolorclosestalpha($image, 155, 40, 200, 50);
$output = imagecolorsforindex($image, $output);
$output = "({$output['red']}, {$output['green']},
{$output['blue']}, {$output['alpha']})";
echo "Closest match: " . $output . "\n";
imagedestroy($image);
?>
ผลลัพธ์ที่ได้
Closest match: (100, 58, 108, 0)
ตัวอย่างที่สอง
<?php
// Convert an image into a palette-based image
$image = imagecreatefrompng(
'https://cdncontribute.geeksforgeeks.org/wp-content/uploads/col1.png');
imagetruecolortopalette($image, false, 255);
// Search the given rgb color.
$color = array(
array(155, 40, 200, 50),
array(235, 205, 188, 127),
array(135, 00, 132, 0),
);
// Loop to return the closest color match.
foreach($color as $id => $rgb)
{
$output = imagecolorclosestalpha($image, $rgb[0],
$rgb[1], $rgb[2], $rgb[3]);
$output = imagecolorsforindex($image, $output);
$output = "({$output['red']}, {$output['green']},
{$output['blue']}, {$output['alpha']})";
echo "Given color: ($rgb[0], $rgb[1], $rgb[2], $rgb[3])
=> Closest match: $output <br>";
}
imagedestroy($image);
?>
ผลลัพธ์ที่ได้
Given color: (155, 40, 200, 50) => Closest match: (100, 58, 108, 0)
Given color: (235, 205, 188, 127) => Closest match: (100, 58, 108, 0)
Given color: (135, 0, 132, 0) => Closest match: (100, 58, 108, 0)
จากผลลัพธ์เราจะเห็นได้ สามารถรับค่า index สีของClosest ได้ สามารถนำไปใช้ประโยช์ดูน่ะครับ