Web Info and IT Lessons Blog...

Sunday, 19 April 2015

Convert a string to an image in PHP

The previous lesson of PHP Lessons Series was about drawing image patterns using imagesetpixel() function and in this lesson we will learn to convert a string to an image in PHP.

Convert String to Image In PHP

You need to know about imagecolorallocate() and imagesetpixel() functions discussed in the previous lessons as pre-requisite for this lesson. In this lesson we will convert each character of a string to it's ASCII value and set the rgb colour value of every pixel of the image equal to the ASCII value of one character of the string. In other words, each pixel of the image will represent a character of the string. The php code for converting a string to an image is given below:


<?php
header('Content-type: image/png');

$string = 'Hello world! I am getting converted to an image...';
$strArr = str_split($string);
$width = ceil(sqrt(sizeOf($strArr)));
$height = ceil(sqrt(sizeOf($strArr)));
$image = imagecreatetruecolor($width, $height);
$allocateColor = imagecolorallocate($image,255,255,255);
$count = 0;
for($i=0;$i<$width;$i++){
 for($j=0;$j<$height;$j++){
  if($count < sizeOf($strArr)){
   $asciiVal = ord($strArr[$count]);
   $count++;
   $colour = imagecolorallocate($image,$asciiVal,$asciiVal,$asciiVal);
   imagesetpixel($image, $i, $j, $colour);
   
  }
 }
}
imagepng($image,'new.png');
imagedestroy($image);
?>

In the above code the string to convert to an image is:


$string = 'Hello world! I am getting converted to an image...';

The first thing we need to know is the width and height of the image to create. The width and height of the image depends upon the size of the string. Forexample, If the string is 64 characters long then we need 64 pixels to store the string which means that we need 8X8 image to do the job. The width and height in the script are calculated like this:


$width = ceil(sqrt(sizeOf($strArr)));
$height = ceil(sqrt(sizeOf($strArr)));

Once we know the width and height of the image, we will create a new image using imagecreatetruecolor() function. After the image is created, we have to allocate a color to the image. The nested for loop is then used to traverse each pixel of the image and assign it a colour (rgb values equal to the ASCII value of a character) if the size of string is not exceeded. When all the pixels of the image are set, a png image named 'new.png' is created in the same folder where your php script is located. Your png image should look something like this:

String Converted to Image

In the next lesson we will learn to convert the image back to the string using php. Stay tuned for more lessons!

Related Posts
How to create an image in PHP?
Drawing image patterns using imagesetpixel() in PHP
Convert an image to a string in PHP
Write text to image in php using imagettftext()

No comments:

Post a Comment