Archive for the 'PHP' Category

05
Sep

Simple background removal with PHP and GD.

I haven’t posted in awhile, but I got a short, article on background removal in images using PHP and the GD image library.

The way I did this is take a specified image and a specified color to look for as well as a difference or a maximum difference in each color allowed. After that it will take the values entered for each of the items just listed and go through each pixel looking for the colors in the range specified. If the pixel color is not within range, it set’s the color to white, or black depending on the color you are looking for. Anyhow here are the functions which do this.

Firstly HexToRGB which will turn an Hexadecimal color value to RGB integer values.

function HexToRGB($hex) {
        $hex = str_replace("#", "", $hex);
        $colors = array();

        if(strlen($hex) == 3) {
            $colors['r'] = hexdec(substr($hex, 0, 1) . $r);
            $colors['g'] = hexdec(substr($hex, 1, 1) . $g);
            $colors['b'] = hexdec(substr($hex, 2, 1) . $b);
        }
        else if(strlen($hex) == 6) {
            $colors['r'] = hexdec(substr($hex, 0, 2));
            $colors['g'] = hexdec(substr($hex, 2, 2));
            $colors['b'] = hexdec(substr($hex, 4, 2));
        }
        $colors;
    }

Last is the RemoveBackground function, which is the one that does all the hard work. It scans the image and removes unwanted colors. But is quite and simple function. As of right now it just draws the image to the browser as a png, but that is easily modified.

You will have to play around with the difference when calling the RemoveBackground function to get your desired results.

function RemoveBackground($image, $foregroundColor, $difference = 0) {
        if(file_exists($image)) {
            list($width, $height, $type) = getimagesize($image);
            $ext = strtolower(array_pop(explode(".", $image)));
            $img = null;

            switch($ext) {
                case "jpg":
                case "jpeg":
                    $img = imagecreatefromjpeg($image);
                    break;
                case "png":
                    $img = imagecreatefrompng($image);
                    break;
                case "gif":
                    $img = imagecreatefromgif($image);
                    break;
                case "bmp":
                    $img = imagecreatefromwbmp($image);
                    break;
                case "xbm":
                    $img = imagecreatefromxbm($image);
                    break;
                case "xpm":
                    $img = imagecreatefromxpm($image);
                    break;
            }

            if($img != null) {
                list($r, $g, $b) = HexToRGB($foregroundColor);
                $color = imagecolorallocate($img, $r, $g, $b);
                $white = imagecolorallocate($img, 255, 255, 255);
                $black = imagecolorallocate($img, 0, 0, 0);

                for($x = 0; $x < $width; $x++) {
                    for($y = 0; $y < $height; $y++) {
                        $pixelColor = imagecolorat($img, $x, $y);
                        $pixelR = ($pixelColor >> 16) & 0xFF;
                        $pixelG = ($pixelColor >> 8) & 0xFF;
                        $pixelB = $pixelColor & 0xFF;

                        if($pixelR < ($r - $difference) || $pixelR > ($r + $difference) ||
                            $pixelG < ($g - $difference) || $pixelG > ($g + $difference) ||
                            $pixelB < ($b - $difference) || $pixelB > ($b + $difference)) {
                            if($color != $white) {
                                imagesetpixel($img, $x, $y, $white);
                            }
                            else {
                                imagesetpixel($img, $x, $y, $black);
                            }
                        }
                        else {
                            imagesetpixel($img, $x, $y, $pixelColor);
                        }
                    }
                }
                header("Content-Type: image/png");
                imagepng($img, null);
            }
        }
    }

It is a simple as that. Below is a zip file containing the functions above, as well as a test image.
Background Removal (38)

24
Jul

SimpleMail - Easily send email’s with attachments from php.

Here is a pretty simple class that uses the default mail function so no sockets or direct connections to server’s
have to be used. But this script will allow you to add multiple contacts, as well as multiple attachments, easily.

It is as simple as this.

<?php
    include "SimpleMail.php";
    $mail = new SimpleMail("test@domain.com", "test@test.com", "This is a test message");

    $msg = "This is a quick test message, just sending some attachments\n";
    $msg.= "with this test email, yeah";

    $mail->AddMessage($msg);
    $mail->AddAttachment("test.txt");
    $mail->AddAttachment("test.png");
    $mail->AddAttachment("test.jpg");

    if($mail->SendMessage()) {
        echo "Your message was sussecfully sent";
    }
    else {
        echo "Your message failed to send, please try again later";
    }
?>

Hope someone finds it useful, enjoy.
SimpleMail (69)

23
Jul

Create image preview of textfile with PHP and the GD library.

This will be a small tutorial on how to create preview images / thumbnails of textfiles using PHP and the built-in GD library.
Note: This tutorial requires that you have GD2+ with Freetype support.

Ok so lets get started. This is actually quite an easy task, the basic idea is that we read in the lines of the
textfile convert tabs to spaces, and then draw each line to the image file we have created, easy huh?

First things first lets create the function name and arguments.

function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {

}

Ok we now have are function and are ready to start adding code, but first a brief overview of
what each argument is for.

$textSource - The textfile to read from.
$thumbDesc - The path to save the image, use null to display in browser.
$width - The width of the image.
$height - The height of the image.
$useEntireFile - Use the entire file for the preview or just the first few lines.

Now that we have got that out of the way, lets start adding are code.
Firstly we will want to check a couple of arguments, as well as checking for are
fontfile.

if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
        if($useEntireFile)
            $fontSize = 4;
        else
            $fontSize = 7;

Ok that will check that the text file and font file exists as well ad checking whether of not
the text file is readable.

Now we can load are text file, get the maximum number of lines to draw
and set up are image and colors.

$lines = file($textSource);
$lineHeight = ($fontSize + 2);
$maxLines = ($height / $lineHeight);

$thumb = imagecreatetruecolor($width, $height);
$black = imagecolorallocate($thumb, 0, 0, 0);
$white = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0, 0, $white);

Ok now all that is left is to draw the lines and save the image.

for($i = 1; $i < $maxLines + 1; $i++) {
            $line = str_replace("\t", "    ", $lines[$i]);
            imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
        }

        if(!imagepng($thumb, $thumbDest)) {
            return false;
        }
        return true;

Ok and there it is, I used png because png is the better format for save images which contain alot of text.
But now you probaly want the whole thing, so here you go.

<?php
/*
    FileToThumb - Creates a thumbnail preview of a textfile.
    arg1 = textfile to create preview of.
    arg2 = destination of thumbnail preview. (Use null to display to browser)
    arg3 = width of thumbnail.
    arg4 = height of thumbnail.
    arg5 = true or false for using the entire file or the first few
        lines for the thumbnail.
*/

function FileToThumb($textSource, $thumbDest, $width, $height, $useEntireFile) {
    if(file_exists($textSource) && is_readable($textSource) && file_exists("arial.ttf")) {
        if($useEntireFile)
            $fontSize = 4;
        else
            $fontSize = 7;

        $lines = file($textSource);
        $lineHeight = ($fontSize + 2);
        $maxLines = ($height / $lineHeight);

        $thumb = imagecreatetruecolor($width, $height);
        $black = imagecolorallocate($thumb, 0, 0, 0);
        $white = imagecolorallocate($thumb, 255, 255, 255);
        imagefill($thumb, 0, 0, $white);

        for($i = 1; $i < $maxLines + 1; $i++) {
            $line = str_replace("\t", "    ", $lines[$i]);
            imagettftext($thumb, $fontSize, 0, 2, ($i * $lineHeight), $black, "arial.ttf", $line);
        }

        if(!imagepng($thumb, $thumbDest)) {
            return false;
        }
        return true;
    }
}
?>

Here is a simple example of the output of the function using this statment.

FileToThumb("test.txt", "test.png", 80, 120, false);

test

There is your ready to use function for creating image previews of textfiles, enjoy.

08
Jul

Simple Fuzzy Search with PHP

Approximate string search or Fuzzy string search, can be a difficult task if you have a very sophisticated searching / matching algorithm. So today I will show you a quite simple Fuzzy string search and use it to create a small efficient search application.

The CompareStrings method that we have ready is what we check a word against our search and give us back a value of difference (or threshold) from our search and the word we are checking. It does this by first checking each character while also checking for case insensitive or not, any difference in case if it applies or the character will add one to the threshold. We then check the length and add one for each single character difference in length. After all that we return the threshold and from there we can check the threshold to see if the word is something we want to keep and do something with. So before we do anything else, lets take a look at the CompareStrings function / method.

function CompareStrings($str1, $str2, $caseInsensitive = false) {
	$threshold = 0;

	if(strlen($str1) != strlen($str2)) {
		if(strlen($str1) > strlen($str2)) {
			$threshold = strlen($str1) - strlen($str2);
		}
		else if(strlen($str2) > strlen($str1)) {
			$threshold = strlen($str2) - strlen($str1);
		}
	}

	for($i = 0; $i < strlen($str1); $i++) {
		if($i <= strlen($str2) - 1) {
			if($caseInsensitive) {
				if(strtolower($str1{$i}) != strtolower($str2{$i})) {
					$threshold++;
				}
			}
			else {
				if($str1{$i} != $str2{$i}) {
					$threshold++;
				}
			}
		}
	}
	return $threshold;
}

So you can now see how it checks words, it’s not really difficult but also could be much more intelligent. So now lets start with our search method, “PreformSearch”. This will be a simple method that just checks the threshold and if it is within are acceptable limits we will store the word in an array, after we have sorted through the entire string we then return the array.

First lets set up the method and it’s arguments, as well as are array to store are matches.

function PreformSearch($search, $string, $threshold = 1, $caseSensitive = false) {
	$matches = array();
}

Ok we have that now lets start adding some searching abilities into are new function / method.
We are going to check that the string to search is actually a string and is longer then 0 characters.

if(isset($string) &amp;&amp; strlen($string) > 0) {

}
return $matches;

Now that is out of the way, we can now break up the string, loop though it and check for are matches.

$words = explode(" ", $this->string);

foreach($words as $word) {
        if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
                $matches[] = $word;
        }
}

There, that is all that is needed, so lets see the whole thing all together.

function PreformSearch($search, $threshold = 1, $caseSensitive = false) {
	$matches = array();

	if(isset($this->string) &amp;&amp; strlen($this->string) > 0) {
		$words = explode(" ", $this->string);

		foreach($words as $word) {
			if(CompareStrings($search, $word, $caseInsensitive) <= $threshold) {
                                $matches[] = $word;
                        }
		}
	}
	return $matches;
}

and there it is. That is all that is needed for a very simple fuzzy string search using PHP.
So as you can see the above functions give you a base to start a much more sophisticated search then what is seen
here.

Below is a download to a FuzzySearch class, and a couple of test’s using it.

Fuzzy Search for PHP (90)