Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* Implement word wrapping... Ughhh... why is this NOT done for me!!!
- OK... I know the algorithm sucks at efficiency, but it's for short messages, okay?
- Make sure to set the font on the ImagickDraw Object first!
- @param image the Imagick Image Object
- @param draw the ImagickDraw Object
- @param text the text you want to wrap
- @param maxWidth the maximum width in pixels for your wrapped "virtual" text box
- @return an array of lines and line heights
- */
- function wordWrapAnnotation(&$image, &$draw, $text, $maxWidth)
- {
- $words = explode(" ", $text);
- $lines = array();
- $i = 0;
- $lineHeight = 0;
- while($i < count($words) )
- {
- $currentLine = $words[$i];
- if($i+1 >= count($words))
- {
- $lines[] = $currentLine;
- break;
- }
- //Check to see if we can add another word to this line
- $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
- while($metrics['textWidth'] <= $maxWidth)
- {
- //If so, do it and keep doing it!
- $currentLine .= ' ' . $words[++$i];
- if($i+1 >= count($words))
- break;
- $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
- }
- //We can't add the next word to this line, so loop to the next line
- $lines[] = $currentLine;
- $i++;
- //Finally, update line height
- if($metrics['textHeight'] > $lineHeight)
- $lineHeight = $metrics['textHeight'];
- }
- return array($lines, $lineHeight);
- }
- /* Create some objects */
- $image = new Imagick();
- $draw = new ImagickDraw();
- $pixel = new ImagickPixel( '#2F6EB9' );
- $filename = "products.txt";
- $dir = "product_images/";
- $lines = file($filename, FILE_IGNORE_NEW_LINES);
- foreach ($lines as $line) {
- /* New image */
- $image->newImage(300, 300, $pixel);
- /* Black text */
- $draw->setFillColor('white');
- /* Font properties */
- $draw->setFont('Arial');
- $draw->setFontSize( 30 );
- $draw->setGravity (Imagick::GRAVITY_CENTER);
- list($titles, $lineHeight) = wordWrapAnnotation($image, $draw, $line, 280);
- for($i = 0; $i < count($titles); $i++) {
- $image->annotateImage($draw, 0, 0 + $i*$lineHeight, 0, $titles[$i]);
- }
- /* Create text */
- //$image->annotateImage($draw, 0, 0, 0, $line);
- /* Give image a format */
- $image->setImageFormat('png');
- $image->readImageBlob($image);
- file_put_contents( $dir . preg_replace('/\//', ' ', $line, 2) . ".png", $image);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement