Archive for the 'code.' 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 (70)

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.

07
Jul

SpellChecker.

I am currently in the process of writing my own spell checking library, pretty much just because it’s a good learning experince and because I can. Anyway it seems to work pretty good so far, it is quite simple though uses the following steps to accomplish spell checking.

  1. Check current word in dictionary/list of words.
  2. If no exact match is found(case insensitive or not) then it starts matching.
  3. Matching the words involves going though each word in list and comparing the strings.
  4. Strings are compared by a CompateStrings method that rates string2 against string1 on a 100 point scale.
  5. Words that come withing a certain point limit of string1 will be added to a list of possible suggestions and returned.

This all seems to work pretty good, quite quickly for how it does it, but then I have not done any 10,000+ word dictionary / list searches yet, but I will soon and update with some speed results.

But back to the CompareStrings method, this method gives both strings 100 points, and rates string2 against string1 it first gets how many points each char are worth, afterwards compares each char in string1 to string2 a certain points per char are lost for each character that does not match, afterwards it checkers for the lengths and then multiplies the points per char to the difference in chars and returns the score that string2 got. Pretty simple, but pretty effective so far.

Anyways I will post a downlod to the current version quite soon, I have still got to implement a couple of things, maybe also make suggestion searches a little better.

05
Jul

NotificationBar - Free .NET control.

So I got a free control here for you. It is a pretty simple control, completly in C#. It is a notification/information bar, like that found in IE when you try to download something.

NotificationBar Example.Screenshot of notification bar and demo under linux.

Features of this control include.

  • LGPL License.
  • Easy to use.
  • Works on Mono.
  • Automatically resizes to fit text.
  • Can play system sound when shown.
  • Can flash control any number of times for any number of milliseconds.
  • Can show a ContextMenuStrip when clicked.
  • Useful for when you don’t want to show a MessageBox but want to give the user some info.
  • Uses .NET 2.0.
  • Written in C#.

It comes with a demo project and you can download it here - NotificationBar.zip (343)