Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Font with texture

Status
Not open for further replies.

arst06d

Programmer
Nov 29, 2002
324
Hi

Is this possible using CSS?

I have an image which I want to use as the texture for some text. There is the background-image property to set for the font, but I cannot get the texture to show.

Can I set the font color to transparent in some way, to show the background texture?

Thanks in advance.
 
Nope, this is not possible with the current technology. If you will want that, you will need to resort to images.
 
I was afraid of that. Thanks anyway.
 
There is a roundabout way of doing this, and it is fairly limited, but it can be done.

Problems with it:
1. You have to create a texture image that uses only 2 colors... the color of your background, and transparent.
2. You will have to precisely position the image.

Benefits:
1. It requires very little coding to accomplish.

Basically, create a texture image with 2 different colors... transparent and then the same color as your background (if you use a png file, beware that you have to use a script that enables the alpha transparency in IE, which if you use it too much will significantly slow down the load of your page). Then create a div or similar element that has the text that you want. Now create a floating element inside the element with the text that has relative positioning. Inside of the floating element, place the texture image that you created.

Now, even though it's limited, your font will seem to have a texture to it.

It will be according to taste, as some developers might think it's a cheap and/or tacky solution to the issue, and it is very limited. Bottom line is that it is something that you could try, and not invest boat loads of time trying to figure out. You try it, and if you like it you use it, otherwise you sit on your hands and wait for there to be a real CSS way to texture font.
 
I seem to be having a total brain fart, but I do not at all understand this method.
 
Even if I could understand it I don't think it would give me what I want, having regard to the colour limitations.

Back to images ..
 
I never said it was a good method, but it's the only way (however limited it may be) that I've figured out how to add texture to text.

Here's a more elaborate description of how it works...

Ok, let's say you have a white background and black text.

The image you would make would consist of white and transparent pixels.

When you put this over the text, the white will cover parts of the text, and the transparent will let the text show through certain pixels. This way, users don't know that it's an image over the text, since there's no border and the colors blend into the background.

I've only used this once in testing just to see what would happen.

I've never actually used it on a website, because it never met what I needed (but hey, one mans trash...).

Also, texture is different for different people. Some people think that textures are simply a seamless repeating image, but I look at it differently. Textures to me is a subtle overlay that you add to an image that gives it more than just tht flat look (ie: creating a concrete or rocky kind of texture on a basic color background).

Exactly where is the point that you are assassinated rather than murdered?
 
i'm sure with php/perl you could used the GD module and produce an image which is the text with effect you want.

I use this method to enable me to included more fonts that is standard web fonts for text, it takes the text, uses the TTF, create an image and I display that instead.

I'm sure you could add a BG colour/pattern to the final generated image.

this is the PHP I use , might not be what you want though.
Code:
<?php
/*
    Dynamic Heading Generator
    By Stewart Rosenberger
    [URL unfurl="true"]http://www.stewartspeak.com/headings/[/URL]    

    This script generates PNG images of text, written in
    the font/size that you specify. These PNG images are passed
    back to the browser. Optionally, they can be cached for later use. 
    If a cached image is found, a new image will not be generated,
    and the existing copy will be sent to the browser.

    Additional documentation on PHP's image handling capabilities can
    be found at [URL unfurl="true"]http://www.php.net/image/[/URL]    
*/


[b]$font_file  = 'path_to_TTF files/TTF/' .  $_GET['font'];[/b]
$font_size = $_GET['size'] ;
$font_color = '#' . $_GET['col'] ;
$background_color = '#' . $_GET['bg'] ;

/*
$font_file  = 'font.TTF' ;
$font_size  = 10 ;
$font_color = '#FFFFFF' ;
$background_color = '#374B9C' ;
*/

$transparent_background  = true ;
$cache_images = true ;
$cache_folder = 'cache' ;







/*
  ---------------------------------------------------------------------------
   For basic usage, you should not need to edit anything below this comment.
   If you need to further customize this script's abilities, make sure you
   are familiar with PHP and its image handling capabilities.
  ---------------------------------------------------------------------------
*/

$mime_type = 'image/png' ;
$extension = '.png' ;
$send_buffer_size = 4096 ;

// check for GD support
if(!function_exists('ImageCreate'))
    fatal_error('Error: Server does not support PHP image generation') ;

// clean up text
if(empty($_GET['text']))
    fatal_error('Error: No text specified.') ;
    
$text = $_GET['text'] ;
if(get_magic_quotes_gpc())
    $text = stripslashes($text) ;
$text = javascript_to_html($text) ;

// look for cached copy, send if it exists
$hash = md5(basename($font_file) . $font_size . $font_color .
            $background_color . $transparent_background . $text) ;
$cache_filename = $cache_folder . '/' . $hash . $extension ;
if($cache_images && ($file = @fopen($cache_filename,'rb')))
{
    header('Content-type: ' . $mime_type) ;
    while(!feof($file))
        print(($buffer = fread($file,$send_buffer_size))) ;
    fclose($file) ;
    exit ;
}

// check font availability
$font_found = is_readable($font_file) ;
if(!$font_found)
{
    fatal_error('Error: The server is missing the specified font.') ;
}

// create image
$background_rgb = hex_to_rgb($background_color) ;
$font_rgb = hex_to_rgb($font_color) ;
$dip = get_dip($font_file,$font_size) ;
$box = @ImageTTFBBox($font_size,0,$font_file,$text) ;
$image = @ImageCreate(abs($box[2]-$box[0]),abs($box[5]-$dip)) ;
if(!$image || !$box)
{
    fatal_error('Error: The server could not create this heading image.') ;
}

// allocate colors and draw text
$background_color = @ImageColorAllocate($image,$background_rgb['red'],
    $background_rgb['green'],$background_rgb['blue']) ;
$font_color = ImageColorAllocate($image,$font_rgb['red'],
    $font_rgb['green'],$font_rgb['blue']) ;   
ImageTTFText($image,$font_size,0,-$box[0],abs($box[5]-$box[3])-$box[1],
    $font_color,$font_file,$text) ;

// set transparency
if($transparent_background)
    ImageColorTransparent($image,$background_color) ;

header('Content-type: ' . $mime_type) ;
ImagePNG($image) ;

// save copy of image for cache
if($cache_images)
{
    @ImagePNG($image,$cache_filename) ;
}

ImageDestroy($image) ;
exit ;


/*
	try to determine the "dip" (pixels dropped below baseline) of this
	font for this size.
*/
function get_dip($font,$size)
{
	$test_chars = 'abcdefghijklmnopqrstuvwxyz' .
			      'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .
				  '1234567890' .
				  '!@#$%^&*()\'"\\/;.,`~<>[]{}-+_-=' ;
	$box = @ImageTTFBBox($size,0,$font,$test_chars) ;
	return $box[3] ;
}


/*
    attempt to create an image containing the error message given. 
    if this works, the image is sent to the browser. if not, an error
    is logged, and passed back to the browser as a 500 code instead.
*/
function fatal_error($message)
{
    // send an image
    if(function_exists('ImageCreate'))
    {
        $width = ImageFontWidth(5) * strlen($message) + 10 ;
        $height = ImageFontHeight(5) + 10 ;
        if($image = ImageCreate($width,$height))
        {
            $background = ImageColorAllocate($image,255,255,255) ;
            $text_color = ImageColorAllocate($image,0,0,0) ;
            ImageString($image,5,5,5,$message,$text_color) ;    
            header('Content-type: image/png') ;
            ImagePNG($image) ;
            ImageDestroy($image) ;
            exit ;
        }
    }

    // send 500 code
    header("HTTP/1.0 500 Internal Server Error") ;
    print($message) ;
    exit ;
}


/* 
    decode an HTML hex-code into an array of R,G, and B values.
    accepts these formats: (case insensitive) #ffffff, ffffff, #fff, fff 
*/    
function hex_to_rgb($hex)
{
    // remove '#'
    if(substr($hex,0,1) == '#')
        $hex = substr($hex,1) ;

    // expand short form ('fff') color
    if(strlen($hex) == 3)
    {
        $hex = substr($hex,0,1) . substr($hex,0,1) .
               substr($hex,1,1) . substr($hex,1,1) .
               substr($hex,2,1) . substr($hex,2,1) ;
    }

    if(strlen($hex) != 6)
        fatal_error('Error: Invalid color "'.$hex.'"') ;

    // convert
    $rgb['red'] = hexdec(substr($hex,0,2)) ;
    $rgb['green'] = hexdec(substr($hex,2,2)) ;
    $rgb['blue'] = hexdec(substr($hex,4,2)) ;

    return $rgb ;
}


/*
    convert embedded, javascript unicode characters into embedded HTML
    entities. (e.g. '%u2018' => '&#8216;'). returns the converted string.
*/
function javascript_to_html($text)
{
    $matches = null ;
    preg_match_all('/%u([0-9A-F]{4})/i',$text,$matches) ;
    if(!empty($matches)) for($i=0;$i<sizeof($matches[0]);$i++)
        $text = str_replace($matches[0][$i],
                            '&#'.hexdec($matches[1][$i]).';',$text) ;

    return $text ;
}

?>


you then call it like this, passing font,colour,size,text...
Code:
<img src="URL_TO_DOMAIN/heading.php?text=MY%20TEXT%20HERE&amp;font=NEURPOLI.TTF&amp;size=30&amp;col=0066CC&amp;bg=FFFFFF" alt="alt text" />

Remeber the bit in bold at the top of the script is the path to where you have all the .TTF files, you can easily obtain all the TTF files for all the fonts in your C:\WINDOWS\FONTS folder ;-)


"In complete darkness we are all the same, only our knowledge and wisdom separates us, don't let your eyes deceive you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top