POINT TO PIXEL

Mark Phillips mbp at GEOMTECH.COM
Fri Jun 10 10:01:53 PDT 2005


Below is a php function that I find really handy for converting
between pixels coordinates and map coordinates.  It's simply a general
linear transformation for mapping one rectangular coordinate system to
another.  You pass the "extent" of both rectangles in as arguments, as
well as the point you want to convert.  For pixel coordinates, the
"extent" is simply (0,0) to (width,height).  The same function can be
used to transform coordinates in both directions: either from pixel
coordinate to map coordinates, or the other way.  The direction is
determined by the order in which you pass the arguments.  If you
format your code like this (be sure to view this message with a
fixed-width font):

    linear_interp_2D($a1, $a2,  $b1, $b2,
                     $A1, $A2,  $B1, $B2,
                           $x,        $y)

so that the first 4 arguments line up with the next 4, it's easy to
keep track of the fact that this call returns the image of the point
($x,$y) under the transformation taking ($a1,$a2) to ($A1,$A2) in the
horizontal direction, and ($b1,$b2) to ($B1,$B2) in the vertical
direction.  You reverse the direction of the transformation by
swapping the 1st 4 arguments with the 2nd 4; the code below has an
example.

<?
function linear_interp_2D($a1, $a2,  $b1, $b2,
                          $A1, $A2,  $B1, $B2,
                          $x,        $y) {
  # Return the image of ($x,$y) under the linear transformation
  # taking the rectangle ($a1,$b1) X ($a2,$b2) to the
  # rectangle ($A1,$B1) X ($A2,$B2).
  return array(linear_interp($a1, $a2, $A1, $A2, $x),
               linear_interp($b1, $b2, $B1, $B2, $y));
}

function linear_interp($a1, $a2, $A1, $A2, $x) {
  # Return the image of $x under the linear transformation
  # taking the interval [$a1,$a2] to [$A1,$A2]
  return ($x - $a1) * ($A2 - $A1) / ($a2 - $a1) + $A1;
}

$img1 = linear_interp_2D(    0,   600,     0,  400,
                         -84.0, -83.0,  34.0, 35.0,
                                   10,          45);

printf("%f %f\n", $img1[0], $img1[1]);
# the above prints -83.983333 34.112500

$img2 = linear_interp_2D(-84.0, -83.0,  34.0, 35.0,
                             0,   600,     0,  400,
                           -83.983333,   34.112500);

printf("%f %f\n", $img2[0], $img2[1]);
# the above prints 10.000200 45.000000
?>

Hope this helps,

--Mark

Mark Phillips @ Geometry Technologies LLC
77 Owenby Cove Road
Fairview, NC  28730
Phone: 828-628-0489
mbp at geomtech.com       http://www.geomtech.com



More information about the MapServer-users mailing list