Core PHP

Antialiased Lines with GD

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

AntialiasedLines.php

<?php

	function SmoothLine(&$qrImage, $dX1, $dY1, $dX2, $dY2, $qColor, $dLineWidth) {
		// Get the vector along the line
		$dDeltaX = $dX2 - $dX1;
		$dDeltaY = $dY2 - $dY1;
		$dVectorLength = sqrt($dDeltaX*$dDeltaX + $dDeltaY*$dDeltaY);
		$dUnitX = $dDeltaX/$dVectorLength;
		$dUnitY = $dDeltaY/$dVectorLength;
		// Rotate positive, counter-clockwise, or left: x' = -y, y' = x
		$dPerpUnitX = -$dUnitY;
		$dPerpUnitY = $dUnitX;
		$dFirstX = $dX1 - ($dLineWidth/2)*($dPerpUnitX + $dUnitX);
		$dFirstY = $dY1 - ($dLineWidth/2)*($dPerpUnitY + $dUnitY);
		$dLineLength = $dVectorLength + $dLineWidth;
		$iWidth		= ImageSX($qrImage);
		$iHeight	= ImageSY($qrImage);
		$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
				// 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;
						// Translate the point by subtracting the first point
						$dTransX = $dX - $dFirstX;
						$dTransY = $dY - $dFirstY;
						$dProj = $dUnitX*$dTransX + $dUnitY*$dTransY;
						$dProjPerp = $dPerpUnitX*$dTransX + $dPerpUnitY*$dTransY;
						if (($dProj >= 0) && ($dProj <= $dLineLength) &&
							($dProjPerp >= 0) && ($dProjPerp <= $dLineWidth)) {
							$iWeight += $iaWeights[$iXF]*$iaWeights[$iYF];
						}
					}
				}
				// Adjst the alpha channel based on the weight
				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
					$qPixel = ImageColorExactAlpha($qrImage,
						$qColor['R'], $qColor['G'], $qColor['B'],
						(127 - 127*sqrt($iMaxWeight*$iWeight)/$iMaxWeight));
					ImageSetPixel($qrImage, $i, $j, $qPixel);
				}
			}
		}
	}

    $qImage = ImageCreateTrueColor(320, 240);

	// Draw two lines
    SmoothLine($qImage, 290, 40, 30, 90, array( 'R' => 0x70, 'G' => 0xC0, 'B' => 0x88 ), 5.0);
    SmoothLine($qImage, 30, 40, 270, 190, array( 'R' => 0xF0, 'G' => 0xA0, 'B' => 0x0 ), 14.0);

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

Output

 
 

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