以下程式碼可能很有用。它可以將圖片中心最大的圓形區域提取到指定大小的正方形中,並可選擇旋轉。正方形的其餘部分會設為透明,因此適用於覆蓋在其他圖片上。我將其命名為雙筒望遠鏡效果,因為在一些舊的電視節目中,當他們顯示有人在看雙筒望遠鏡時,螢幕會顯示一個帶有黑色邊緣的巨大圓形影像。
<?php
function image_binocular_effect($src, $bearing, $out_square) {
$out = imagecreatetruecolor($out_square, $out_square);
$width=imagesx($src);
$height=imagesy($src);
$square=min($width, $height);
imagecopyresampled($out, $src, 0, 0, ($width - $square)/2 , ($height - $square)/2, $out_square, $out_square, $square, $square);
$mask = imagecreatetruecolor($out_square, $out_square);
$black = ImageColorAllocate ($mask, 0, 0, 0);
$white = ImageColorAllocate ($mask, 255, 255, 255);
imagefilledrectangle($mask , 0, 0, $out_square, $out_square, $white);
$centrexy=$out_square / 2;
imagefilledellipse($mask, $centrexy, $centrexy, $out_square, $out_square, $black);
ImageColorTransparent($mask, $black);
imagecopymerge($out, $mask, 0, 0, 0, 0, $out_square, $out_square, 100);
if ($bearing != 0) {
$rotated_img=imagerotate($out , 360-$bearing, $white);
$rotated_map_width = imagesx($rotated_img);
$rotated_map_height = imagesy($rotated_img);
imagecopy($out, $rotated_img, 0, 0, ($rotated_map_width - $out_square) / 2, ($rotated_map_height - $out_square) / 2, $out_square, $out_square);
}
ImageColorTransparent($out, $white);
return $out;
}
$src = imagecreatetruecolor(200, 50);
imagefilledrectangle($src, 0, 0, 200, 50, imagecolorallocate($src, 255, 255, 255));
ImageString($src, 3, 10, 10, "這是一個範例圖像,用於說明雙筒鏡效果", imagecolorallocate($im, 192, 0, 0));
$img=image_binocular_effect($src, 72, 50);
ImagePNG($img,"test.png");
?>