How can I rotate this hexagon, without rotating the image. I would also like to know how to change the size of the image it already generates, that is, that both the hexagon and the image change size.
This is the script I use.
<?php
// doge.jpg is a squared pic
$raw = imagecreatefromjpeg('img.jpg');
/* Simple math here
A_____F
/ \
B/ \E
\ /
C\_____/D
*/
$w = imagesx($raw);
$points = array(
.25 * $w, .067 * $w, // A
0, .5 * $w, // B
.25 * $w, .933 * $w, // C
.75 * $w, .933 * $w, // D
$w, .5 * $w, // E
.75 * $w, .067 * $w // F
);
// Create the mask
$mask = imagecreatetruecolor($w, $w);
imagefilledpolygon($mask, $points, 6, imagecolorallocate($mask, 255, 0, 0));
// Create the new image with a transparent bg
$image = imagecreatetruecolor($w, $w);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagealphablending($image, false);
imagesavealpha($image, true);
imagefill($image, 0, 0, $transparent);
// Iterate over the mask's pixels, only copy them when its red.
// Note that you could have semi-transparent colors by simply using the mask's
// red channel as the original color's alpha.
for($x = 0; $x < $w; $x++) {
for ($y=0; $y < $w; $y++) {
$m = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
if($m['red']) {
$color = imagecolorsforindex($raw, imagecolorat($raw, $x, $y));
imagesetpixel($image, $x, $y, imagecolorallocatealpha($image,
$color['red'], $color['green'],
$color['blue'], $color['alpha']));
}
}
}
// Display the result
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
This question is divided into two parts:
The first is a simple matter of math (as indicated in the same code you share), the second is just a matter of applying one more function.
How to rotate the hexagon
Right now the hexagon is created by copying the pixels within the area specified in the array
$points
, so all you have to do is recalculate the points.This is what you have now:
To make it a hexagon with the point up change that part, for this code:
The coordinates are a bit of an eyeball and you'll have to recalculate them if you want it to be a perfect hexagon, but they work (more or less well) on my site:
How to scale the image
To scale the image you just need the imagescale() function, which works like this:
So in your case you could do something like this to resize/scale the image to 400 x 400: