Let’s take a moment to examine the two custom methods that embed the avatar and status text into our image. private function embedAvatar(&$image, $avatar, $left, $bottom) { if (file_exists($avatar)) { if (stristr($avatar, '.jpg')) { $aimg = @imagecreatefromjpeg($avatar); } elseif (stristr($avatar, '.png')) { $aimg = @imagecreatefrompng($avatar); } if (!$aimg) { // Unable to create avatar. } $awidth = imagesx($aimg); $aheight = imagesy($aimg); $top = imagesy($image) - $aheight - $bottom; $copied = @imagecopy($image, $aimg, $left, $top, 0, 0, $awidth, $aheight); if (!$copied) { // Unable to add avatar to image. } } } The first of our two custom methods embeds the user’s avatar image that was retrieved from the Twitter web site. Notice that I’ve implemented some logic here to prevent any unnecessary errors if the image was unavailable. The entire operation is enclosed in an If structure that first checks that the local image exists. If it does not, the method will simply return without it. This allows the signature image to be created without an avatar. If the image does exist, we grab its dimensions and calculate some padding. It’s finally embedded using GD’s ImageCopy function. private function embedText(&$image, $text, $left, $top, $tmaxw=300, $font=3) { $fheight = imagefontheight($font); $color = imagecolorallocate($image, 100, 100, 100); $lines = $this->lineWrap($font, $text, $tmaxw); $lmax = floor(imagesy($image) / $fheight); $lcount = (count($lines) > $lmax) ? $lmax : count($lines); $ttop = (imagesy($image) - ($lcount*$fheight)) / 2; $tleft = 2*$left + 48; while ((list($num, $line) = each($lines)) && $num < $lcount) { imagestring($image, $font, $tleft, $ttop, $line, $color); $ttop += $fheight; } } The text is embedded similarly using the ImageString function. This time however, we need to do a little work on the text before we can add it. Since the string may be too long for the image, it first must be truncated and then word-wrapped into multiple lines. To do that, we’ll add one final function to this class. private function lineWrap($font, $text, $maxwidth) { $fwidth = imagefontwidth($font); if ($maxwidth != NULL) { $maxcharsperline = floor($maxwidth / $fwidth); $text = wordwrap($text, $maxcharsperline, "n", 1); } return explode("n", $text); } Here, the lineWrap function truncates and separates the status text into multiple lines. Those lines are then returned as an array back to the embedText method, where they are added to the image. The embedText method contains logic that will auto-center the text vertically based upon the number of lines returned.
blog comments powered by Disqus |
|
|
|
|
|
|
|