How would I skew an image with GD Library?
Asked Answered
I

3

6

I want to skew an image into a trapezoidal shape. The left and right edges need to be straight up and down; the top and left edges need to be angular. I have no idea what the best way to do this is.

I'm using GD Library and PHP. Can anyone point me in the right direction?

Thanks, Jason

Infeld answered 30/10, 2009 at 15:6 Comment(0)
H
5

Try this:

<? 
// Set it up
$img_name = "grid.jpg"; 
$src_img = imagecreatefromjpeg($img_name); 
$magnify = 4;

// Magnify the size
$w = imagesx($src_img); 
$h = imagesy($src_img); 
$dst_img = imagecreatetruecolor($w * $magnify, $h * $magnify);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $w * $magnify, $h * $magnify, $w, $h);
$src_img = $dst_img;

// Skew it
$w *= $magnify;
$h *= $magnify;
$new_lh = abs($h * 0.66); 
$new_rh = $h ; 
$step = abs((($new_rh - $new_lh) / 2) / $w);
$from_top = ($new_rh - $new_lh) / 2 ; 
$dst_img = imagecreatetruecolor($w, $new_rh);
$bg_colour = imagecolorallocate($dst_img, 255, 255, 255); 
imagefill($dst_img, 0, 0, $bg_colour); 
for ($i = 0 ; $i < $w ; $i ++)
{
    imagecopyresampled($dst_img, $src_img, $i, $from_top - $step * $i, $i, 0, 1, $new_lh + $step * $i * 2, 1, $h); 
}

// Reduce the size to "anti-alias" it
$src_img = $dst_img;
$dst_img = imagecreatetruecolor($w / $magnify  * 0.85, $new_rh / $magnify);
imagecopyresampled ($dst_img, $src_img, 0, 0, 0, 0, $w / $magnify * 0.85, $h / $magnify, $w, $h);

header("Content-Type: image/jpg");  
imagejpeg($dst_img); 
?>
Hashish answered 8/6, 2010 at 0:59 Comment(1)
thanks for the solution. do you have for the other side around?Triclinic
L
3

I found this thread (translated Dutch -> English) discussing the same thing. Looks like it might be what you're after. I think it's clear that you can't skew with GD without writing your own function to do so. If you have ImageMagick available, you might find this to be easier to achieve.

Good luck.

Lecialecithin answered 30/10, 2009 at 16:56 Comment(1)
Yes, ImageMagick is what came to my mind, it can do most anything.Winebibber
H
1

Make a nested loop for x = 0 to width and inside y = 0 to height, get pixel (rgba) at that coordinate, calculate new xy for skew rotation (using sine cosine, you have to have skew origin for angle calculation) and then copy pixels to empty image. Just high school math

Hebrides answered 9/10, 2020 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.