Core PHP

Antialiased Circles with GD

This GD example program demonstrates the code for an example program that demonstrates how to draw antialiased circles with GD and create a png image.

AntialiasedCircles.php

<?php
	function SmoothCircle(&$qrImage, $dCX, $dCY, $dCR, $caColor, $iLineWidth) {
		// The alpha channel is between 0 (full) and 127 (transparent).
		// Pixels are centered at integer values.
		// Get the image size
		$iWidth			= ImageSX($qrImage);
		$iHeight		= ImageSY($qrImage);
		$dOuterRadius	= $dCR + ($iLineWidth/2);
		$dInnerRadius	= $dCR - ($iLineWidth/2);
		// A constant filter kernal seems to work best.
		$iaWeights		= Array(2,2,2,2,2);
		$iMaxWeight		= 0;
		for ($iXW = 0; $iXW < 5; ++$iXW) {
			for ($iYW = 0; $iYW < 5; ++$iYW) {
				$iMaxWeight += $iaWeights[$iXW]*$iaWeights[$iYW];
			}
		}
		for ($i = 0; $i < $iWidth; ++$i) {
			for ($j = 0; $j < $iHeight; ++$j) {
				// Filter indices
				// Weight Locations: -.4, -.2, 0, .2, .4
				$iWeight = 0;
				for ($iXF = 0; $iXF < 5; ++$iXF) {
					for ($iYF = 0; $iYF < 5; ++$iYF) {
						$dX = $i + .2*$iXF - .4;
						$dY = $j + .2*$iYF - .4;
						$dDX = $dCX - $dX;
						$dDY = $dCY - $dY;
						$dDist = sqrt($dDX*$dDX + $dDY*$dDY);
						if (($dDist <= $dOuterRadius) && ($dDist >= $dInnerRadius)) {
							$iWeight += $iaWeights[$iXF]*$iaWeights[$iYF];
						}
					}
				}
				// Get the current pixel index
				if ($iWeight != 0) {
					// Reweight using a semicircle to approximate logarithmic response
					// Use a semicircle response curve x/w = y^2/w^2 --> y = sqrt(w*x)/w
					$dPixel = ImageColorExactAlpha($qrImage, $caColor[ 'R' ], $caColor[ 'G' ],
						$caColor[ 'B' ], ( 127 - 127*sqrt($iMaxWeight*$iWeight)/$iMaxWeight));
					ImageSetPixel($qrImage, $i, $j, $dPixel);
				}
			}
		}
	}

	$qImage = ImageCreateTrueColor(320, 240);

	SmoothCircle($qImage, 160, 120, 100, Array( 'R' => 0xFF, 'G' => 0x0, 'B' => 0x0 ), 5.5);
	SmoothCircle($qImage, 170, 150,  75, Array( 'R' => 0xFF, 'G' => 0xFF, 'B' => 0x0 ), .25);

	Header('Content-Type: image/png');
    ImagePNG($qImage);
    ImageDestroy($qImage);
?>
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.