Drupal: Convert Text to transparent png Image with responsive width

This CodeLet create Transparent png image from 'string', with responsive width.

CodeLet: 

function create_question_ans_img($text, $transparent_png_file = 'txt_to_img.png', $width, $wordwrap = 80){
$font_size = 14;
$lines = explode('|', wordwrap($text, $wordwrap , '|'));
$total_lines = count($lines);

// height of
$height = (ImageFontHeight($font_size) * $total_lines) ;

foreach ($lines as $line)
{
$line_width[] = strlen($line) * imagefontwidth($font_size);
}
// get max line width
$max_width = max(array_values($line_width));
//
if($width < $max_width && $wordwrap >= 1) {

$diff = $max_width - ($width);

if($diff > 100 ) {
$wordwrap = $wordwrap - 10;
} else if($diff > 50 ){
$wordwrap = $wordwrap - 5;
}else if($diff > 25 ){
$wordwrap = $wordwrap - 4;
}else if($diff >= 2){
$wordwrap = $wordwrap - 2;
}

return create_question_ans_img($text, $transparent_png_file, $width, $wordwrap);
}

$im = imagecreatetruecolor($width, $height);

imagealphablending($im, false);
imagesavealpha($im, true);

// Create colors and draw transparent background
$trans = imagecolorallocatealpha($im, 255, 255, 255, 127);
$black = imagecolorallocate($im, 0, 0, 0);
$black = imagecolorallocate($im, 255, 0, 0);
imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $trans);

$line_number = 1;
foreach ($lines as $line)
{
$center_x = ceil( ( imagesx($im) - ( ImageFontWidth($font_size) * strlen($line) ) ) / 2 );
$center_y = ceil( ( ( imagesy($im) - ( ImageFontHeight($font_size) * $total_lines ) ) / 2) + ( ($line_number-1) * ImageFontHeight($font_size) ) );
ImageString($im, $font_size, $center_x, $center_y, $line, $black );
$line_number++;
}

// Output PNG
imagepng($im, $transparent_png_file);
}

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

$width = 200; // widh of text image.
create_question_ans_img($text, $transparent_png_file = 'txt_to_img.png', $width, $wordwrap = 80);

By saru1683 on Fri, 26/04/2013 - 5:23pm

Add comment

Log in or register to post comments
QR code for this page URL This page URL
Feedback