linein designs

29 Mar, 2011

Text to Image Using PHP and img4me

Posted by: john In: php|tutorial|web

img4me just released an API to their text to image service. This basically allows you to send any peice of text through a URL and have it convert it into an image. Now you wouldn’t want to convert a whole paragraph, but this does work especially nice for email addresses or other information you don’t want to be crawled by the search bots.

Here is a quick function that allows you to easily add this to any project.

Example | Download Files

function img4me($text,$font,$fcolor,$size,$bcolor,$type)
{
	/*
	Parameters
	text*		= text to be converted. (required)
	font		= arial, comic, georgia, impact, lucida, simsun, tahoma, times, trebuchet, verdana (default: courier)
	size		= font size in number 5-35 (default: 12)
	fcolor	= font color in HEX (default: 000000)
	bcolor	= background color in HEX - leave empty for transparent background
	type		= gif, jpg, png (default: png)
	*/

	if(!empty($text))
	{
		$optional = array('font','fcolor','size','bgcolor','type');
		foreach($optional as $key => $value){
			if(!empty($$value)){$get_prams .= '&'.$value.'='.$$value;}
		}
		
		$url = 'http://api.img4me.com/?text='.urlencode($text).$get_prams;
		
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($ch, CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		$return_data = curl_exec($ch);
		return '';
	}
	else{return 'error: text was empty';}
}

Things you’ll need:

DEMO | DOWNLOAD PROJECT

We’ll first setup the control div since it should help make things clearer starting here. We have the two rotate buttons (clockwise and anit-clockwise) and the save button to save our final rotated image. We also have an input box that will store the rotated value.




current angle: 

Next we have the javascript function that is going to rotate the images based on the buttons we press. Each time they are pressed it’s going to rotate the images 90 degrees either way. (you can change these value to fit your project)

function updateAngle(image,direction,currentAngle)
{
	var rotateAngle = 0;
	switch (direction)
	{
		case 'anticlockwise':
			if(currentAngle == 0){rotateAngle = -90;}
			else{rotateAngle = parseInt(currentAngle) - 90;}
		break;
		default:
			if(currentAngle == 0){rotateAngle = 90;}
			else{rotateAngle = parseInt(currentAngle) + 90;}
	}
			
	$('#'+image).rotateAnimation({
		animateAngle:rotateAngle
	});
		
	$('#currentAngle').val(rotateAngle); // sets currentAngle value
}

Then we have the AJAX request that will send the image and angle value to the PHP script to be saved.

$(document).ready(function()
{
	$('#saveImage').click(function(){
		$('#save_results').html('saving...'); // display while image is being saved
		$.ajax({
		   type: "POST",
		   url: "saveImageAjax.php",
		   data: "img=image.jpg&angle="+$('#currentAngle').val(), // image value is currently hard-coded due to plugin limitation
		   success: function(msg){
	     		$('#save_results').html(msg);
	   	}
	 	});
	});
});

And finally we have the PHP script that takes the variables and stores a local copy of the rotated image. The script is fairly straight forward, but if you have any questions, please leave me a comment below.

Credits:
rotateImage – PHP function developed by Roshan Bhattara (function included in project files)
iconfinder.com/ – icons

Dave in Michigan contacted me and wanted to know if it was possible to take the script used from this previous post and only display the last X number of pictures uploaded to a directory.

Something to note before you get started though. The script will read the entire directory so if you have a lot of images (more than 1,000) the page will load very slow. (if anyone has a good way to read a directory recursively based on filetime, please let me know)

Requirements:

  1. PHP
  2. jQuery (latest version)
  3. InnerFade plugin (see docs for variables explanations and additional vars)

View Source Code

// Global Variables
$image_dir = "$_SERVER[DOCUMENT_ROOT]/imgs"; // directory on server
$image_relative_path = '/imgs'; // path to images relative to script
$file_types = array('jpg','jpeg','gif','png');
$image_time = '4000'; // seconds each image will display (4000 = 4 seconds)
$max_pictures = 6; // 0 = show all
$sort	= 'desc'; // desc = descending, or leave empty for no sort

if($handle = opendir($image_dir))
{
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $ext_bits = explode(".",$file); // finds file extensions
            foreach($ext_bits as $key => $value){
                if(in_array($value,$file_types)){
                    $filetime = filemtime($image_dir.'/'.$file);
                    $image_array[$filetime] = $file; // file creation time is the key
                }
            }
            
        }
    }
    closedir($handle);
}

if($sort == 'desc'){krsort($image_array);} // reverse sorts array by key

$count = 1;
foreach($image_array as $key => $value)
{
   $image_rotation .= '
  • '; ++$count; if($count > $max_pictures){break;} }
    
    
    
    
      < ?= $image_rotation; ?>

    28 Sep, 2010

    Color Pal for Android

    Posted by: john In: android|apps

    Color Pal logo Need help choosing the correct color palette? Color Pal allows you to quickly browse and search through the most popular and newest color palettes from COLOURlovers.com.

    Easily save palettes to your favorites or email them to a friend.

    NEW FEATURE: Swipe through related palettes. When you’re viewing the palettes details, click on each color to view more details which will also find related palettes. Swipe through them to view them all and click on each of them to view that palette’s details.

    Please visit our feedback forum to report any issues or to suggest any new features.

    24 Aug, 2010

    checks – Android Application

    Posted by: john In: android|apps

    Simple way to manage your uncleared checks. Add a check and then mark it cleared. Choose different currencies and the ability to sort and view all checks. NEW FEATURE: backup and restore from the cloud!

    Please leave a comment below or use our feedback forum to report any bugs or suggest new features.

    Screen Shots

    sign up to receive updates & be on our beta testing team:

    1. Add your subdomain
    You can do this as a normal subdomain or as a standalone domain.

    2. Add your certificate to Plesk
    Use the Plesk control panel to add your certificate. Where the shortcoming comes into play is that Plesk will continue to use the default certificate.

    3. Find your certificate
    Head over to /usr/local/psa/var/certificates

    Take note of the file name cert-xxxxxx that has today’s creation date. There may be two if you installed a CA certificate. You will need to determine which file is the normal certificate and which one is the CA one for the step 5.

    4.Copy the include file
    Go to /var/www/vhosts/sub.domain.com/conf and open the httpd.include file
    Find where it has

    ServerName sub.domain.com:443

    Copy the entire VirtualHost block for JUST the SSL portion. (from <VirtualHost xx.xx.xx.xx:443> to </VirtualHost>)

    5. Make your include file
    Head over to /etc/httpd/conf.d and make a file. Call it something like z0-subdomain.conf. The file just needs to load after ssl.conf but before zz010_psa_httpd.conf. Paste what you copied from step 4 into the file and then set the certificate file names from step 3 into these following places.

    SSLCertificateFile /usr/local/psa/var/certificates/cert-xxxxxx

    If you have a CA certificate, you must also add this line just below:

    SSLCACertificateFile /usr/local/psa/var/certificates/cert-xxxxxx

    6. Restart Apache
    service httpd restart

    Most of these instructions were taking from this page, but they left the CA certificate step. This is very important since certain browsers do not trust all intermediate CA’s. (mostly Apple products and some cell phones)

    Tags:

    This is a more practical way to display an image or text while an AJAX request is loading.

    DEMO | DOWNLOAD FILES

    What we’re basically doing is forcing a DIV to have a starting image and then replacing it with the text return from the AJAX request.

    function loadingAjax(div_id)
    {
    	$("#"+div_id).html(' saving...');
    	$.ajax({
    		type: "POST",
    		url: "script.php",
    		data: "name=John&id=28",
    		success: function(msg){
    			$("#"+div_id).html(msg);
    		}
    	});
    }
    

    Usage

    save page
    

    As always – if you’re looking for a sweet AJAX loading image, check out www.ajaxload.info..

    If you have any questions or *gasp* improvements, please leave me a comment below.

    After searching around for the better part of this morning, I finally figured out why my file upload script was not working correctly. When I setup the domain I did not even check to see if it was turned on since I did it relatively quickly, but right there in the “Hosting Settings” is an option to turn on PHP safe_mode.

    I’m sure there’s a good reason to keep it on when using virtual hosting with multiple people using the same server, but for me it was just causing more problems then I could figure out. If anyone knows how to keep it on while still being able to copy/move files from an upload, please leave a comment below.

    12 Apr, 2010

    Baby Speaks First Word at 18 Days Old

    Posted by: john In: baby|funny|pictures

    Our new son speaks his first word at only 18 days old.

    MOM!

    This is an addition to the Find Time Between Two Dates in PHP post.

    Here is a quick way to find the years and months between two dates using PHP. The dates are not exact since we’re assuming that each year and month has the same number of seconds.

    function yearMonthDifference($start_date, $end_date)
    {
    	// 31556926 seconds in year
    	$years = floor(($end_date - $start_date) / 31556926); 
    	// takes remaning seconds to find months  2629743.83 seconds each month
    	$months = floor((($end_date - $start_date) % 31556926) / 2629743.83); 
    	
    	if($years > 0){
    		if($years > 1){$year_s = 's';} // adds "s" if more than one year
    		$years_display = $years.' year'.$year_s;
    	}
    	if($months > 0){
    		if($months > 1){$month_s = 's';} // adds "s" if more than one month
    		$months_display = $months.' month'.$month_s;
    	}
    	
    	return trim($years_display.' '.$months_display);
    }
    
    // useage
    $start_date = 'January 4, 2008';
    $end_date = 'March 5, 2010';
    echo yearMonthDifference($start_date,$end_date);
    

    If you really want to get fancy, you may want to add a check to make sure the start date is less than the end date. Please post a comment below if you have any questions or suggestions.



    Please Support Our Friends

    Send emails with ease on this SMTP server by JangoSmtp.com.

    Banner
    FreshBooks

    About

    My name is John Veldboom and have been in design and web programing for just over 8 years now. Started off as a hobby in high school but it has developed into a full time job now. I always tell people that if I wasn't doing this at work each day, I would be at home doing it for free. I love it!

    Please visit the contact page to drop me a message.