Hack: Create an Image To Replace a String

There are lots of reasons why you may want to have an image with text in it, rather than the text itself. Maybe you want to hide your email address from bots looking to add it to spam databases. Maybe you want to use words without them being indexed by search engines.

Here is a bit of code you can add to your own custom plugin or functions.php that creates a shortcode emailimage. The contents of the shortcode then get used as text and made into an image. And then that image gets encoded and added as data to the post. So there is never any image “file” created anywhere.

// create an image to replace a string

function wpshortcode_emailimage($atts,$content='') {
	$image = imagecreatetruecolor(strlen($content)*9,16);
	$alpha = imagecolorallocatealpha($image, 0, 0, 0, 127);
	imagesavealpha($image, true);
    imagestring($image,5,0,0,$content,imagecolorallocate($image, 0, 0, 0));
    $imagecontents = ob_get_contents();
    $data = base64_encode($imagecontents);
	return "<img src='data:image/png;base64, {$data}' />";

A lot of the magic is done with the PHP function imagestring. Take a look at the reference to understand the 5 (that’s the font). Note that if you change the font, you may also need to change the *9 so the width of the image is larger or smaller to accommodate the average character width.

Leave a Reply

Your email address will not be published. Required fields are marked *