
example A

example B

example C

example D
While developing the website for PWC I wanted to generate the title graphic using the latest covers for the issues of course my design called for rotating these graphics and scaling them with a drop shadow (example A). The problem that I encountered was that PHP’s rotate function loses the alpha channel information filling it with white instead (example B).
So I decided to use some of PHP’s functionality to overcome the issue. I was however disheartened when I discovered that there isn’t any functionality available to read alpha information from a file (you can read RGB info, and write alpha data, you just can’t read the data from the file with existing graphic functions).
All is not lost though. Because the alpha channel for my graphics were always going to be the same I was able to work around the issue.
Because you are able to read the RGB information from a graphic I created a grayscale image to represent the alpha mask (example C). I then take both the mask image, and the RGB image (example D), and rotate them into place.
Then, pixel by pixel, I read the gray value of the mask image and RGB value of the color image and apply them to my background image. You still have to worry about positioning of the the graphic, and you should make sure your RGB and mask image are the same size (so if you wanted to place an image inside the stamp, you should first scale your replacement image over the RGB of the stamp “background” before rotating and applying the alpha).
This process is slow (the pixel loops are slow), so it’s not something you’d want to be doing often, but for creating images that are saved to disk it works well.
Code example:
$rgb_image = imagecreatefromjpeg('stamp.jpg');
$mask_image = imagecreatefromjpeg('stamp_alpha.jpg');
$background_image = imagecreatefromjpeg('background.jpg');
$rotate = 20; //rotate 20 degrees
//rotate the two images
$rgb_image = imagerotate($rgb_image,$rotate,0x000000);
$mask_image = imagerotate($mask_image,$rotate,0x000000);
//loop through all the images
for ($theX=0;$theX < imagesx ($rgb_image);$theX++){
for ($theY=0;$theY < imagesy($rgb_image);$theY++){
//get the RGB value from the rgb_image
$rgb = imagecolorat($rgb_image,$theX,$theY);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8 ) & 0xFF;
$b = $rgb & 0xFF;
//get the Alpha value from the gray scale mask_image
$rgb = imagecolorat($mask_image,$theX,$theY);
$a = $rgb & 0xFF;
$a = 127-floor($a/2); // The alpha seems to be 7 bit not 8 bit
//set $myColor to the RGB+A
$myColor = imagecolorallocatealpha($rgb_image,$r,$g,$b,$a);
//set the pixel on the background image
imagesetpixel($background_image,($theX),($theY),$myColor);
}
}
//save the image as a JPG on the server
imagejpeg($bacgkround_image,'new_image.jpg',100);