Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tobsn/421165 to your computer and use it in GitHub Desktop.
Save tobsn/421165 to your computer and use it in GitHub Desktop.
really ugly code to generate text within an transparent imagine of a given width without running over the borders (only pixel fonts are supported because of the fixed width)
function formattextimg( $text, $width = 960, $color = array( 0, 0, 0 ), $font = 2 ) {
$width = ( ( isset( $width ) && is_numeric( $width ) ) ? ( ( $width >= 100 ) ? (int)$width : 100 ) : 960 );
$text = str_replace( array( '<b>', '</b>', '<strong>', '</strong>' ), '|', $text );
$text_b = preg_split( '/\|/', $text, -1, PREG_SPLIT_OFFSET_CAPTURE );
foreach($text_b as $k => $tb){if($k%2!=0){$textbold[($tb[1]-1)]=$tb[0];}}
$text = str_replace('|','',$text);
for( $i = 0; $i < strlen( $text ); $i++ ) {
if( $string_c >= ( $width - ( (int)(imagefontwidth( $font ) / 2 ) ) ) ) {
$space = strrpos( $string, ' ' );
$string_sub = substr( $string, 0, $space );
$i = $i - ( strlen( $string ) - $space ) + 1;
$strings[] = $string_sub;
$string = '';
$string_c = 0;
}
$string .= $text{$i};
$string_c += imagefontwidth( $font );
}
$strings[] = $string;
$im = imagecreatetruecolor( $width, ( imagefontheight( $font ) * ( count( $strings ) ) ) );
imagesavealpha( $im, true );
$trans = imagecolorallocate( $im, 255, 255, 255 );
imagefill( $im, 0, 0, $trans );
$color = imagecolorallocate( $im, $color[0], $color[1], $color[2] );
$black = imagecolorallocate( $im, 0, 0, 0 );
foreach( $strings as $pos => $string ) {
imagestring( $im, $font, 0, ( $pos * imagefontheight( $font ) ), $string, $color );
}
$len = 0;
foreach( $strings as $pos => $string ) {
$len += ( strlen( $string ) + 1 );
if( count( $textbold ) > 0 ) {
foreach( $textbold as $cpos => $word ) {
if( $cpos <= $len ) {
$wpos = strpos( $string, $word );
if( $wpos !== false ) {
imagestring( $im, $font,
( $wpos * imagefontwidth( $font ) )+1,
( ( $pos ) * imagefontheight( $font ) ),
$word, $color
);
unset( $textbold[$cpos] );
}
}
}
}
}
return $im;
}
header( 'Content-type: image/png' );
imagepng( formattextimg( $text ) );
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment