David Thomas Baker » Examples » Viewing File: bg.php

<?php

function html2rgb($color,$returnstring=false){
    if (
$color[0] == '#'
       
$color substr($color1);
    if (
strlen($color) == 6)
       list(
$r$g$b) = array($color[0].$color[1],
                                 
$color[2].$color[3],
                                 
$color[4].$color[5]);
    elseif (
strlen($color) == 3)
        list(
$r$g$b) = array($color[0].$color[0], $color[1].$color[1], $color[2].$color[2]);
    else
        return 
false;
    
$key 1;
    
$r hexdec($r)*$key;
    
$g hexdec($g)*$key;
    
$b hexdec($b)*$key;
    if(
$returnstring){
        return 
"{rgb $r $g $b}";
    }else{
        return array(
$r$g$b);
    }
}




// generate a background image with words
$words strtoupper($_REQUEST['w']);
if(!
trim($words))exit;
$all_words explode(" ",$words);
$forecolor html2rgb(($_REQUEST['f'])?$_REQUEST['f']:'000000');
$backcolor html2rgb(($_REQUEST['b'])?$_REQUEST['b']:'FFFFFF');
$fontsize = ($_REQUEST['s'])?$_REQUEST['s']:'12';
$font 'arial.ttf';

// build 4 lines of words
$lines=4;
$current_line=0;
$word_lines=array();
$word_lines_start=array();
$word_lines_y=array();

$word_count count($all_words);
$width 0;
$height 0;
$line_space 10;
$x=0;
$per_line = ($_REQUEST['p'])?$_REQUEST['p']:$word_count+round($word_count/2);
while(
true){
    
$word next($all_words);
    if(
$word===false){
        
$word reset($all_words);
    }
    if(!
$word=trim($word))continue;
    if(
$x++>=$per_line){
        
// work out width of previous line
        
$res imagettfbbox($fontsize,0,$font,$word_lines[$current_line]);
        
$word_lines_start[$current_line] = round(rand(0,100));
        
$width max($width,$res[2]+$word_lines_start[$current_line]);
        
$height += abs($res[5])+$line_space;
        
$word_lines_y[$current_line] = $height;
        
$current_line++;
        
$x=0;
    }
    
$word_lines[$current_line] .= $word."    ";
    if(
$current_line>=$lines)break;
}

// Create the image
$im imagecreatetruecolor($width$height);

// Create some colors
$bg imagecolorallocate($im$backcolor[0],$backcolor[1],$backcolor[2]);
$fc imagecolorallocate($im$forecolor[0],$forecolor[1],$forecolor[2]);
imagefilledrectangle($im00$width$height$bg);

// Add the text
foreach($word_lines as $line_number => $text){
    
imagettftext($im$fontsize0$word_lines_start[$line_number], $word_lines_y[$line_number]-round($line_space/2), $fc$font$text);
}

// Set the content-type
header("Content-type: image/png");

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);



?>