Tag Archives: convert

jQuery Color Picker Plugin: Convert RGB to HEX CodeUnit 08 JUL 2010

I’ve written on the excellent jQuery Color Picker plugin from eyecon.ro before, but a question was recently raised on how to use its RGB output in code. Well actually it turns out that most browsers return its value as a standard HEX color value, but one browser in particular (and I’m not naming names here but it is the one who everyone who think themselves better than the average home user seems to love) returns the value as a RGB color string.

Annoying.

So how to deal with this then?

Well the solution is to run whatever is returned by the color picker on change through a RGB to HEX function, but a function that only fires when working on a RGB string and not a HEX string.

So lets have a look then:

//actual converter function called by main function

function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//function called to return hex string value
function RGBtoHEX(str)
{
	//check that string starts with 'rgb'
	if (str.substring(0, 3) == 'rgb') {
		var arr = str.split(",");
		var r = arr[0].replace('rgb(','').trim(), g = arr[1].trim(), b = arr[2].replace(')','').trim();
		var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
		return "#" + hex.join('');				
	}
	else{
		//string not rgb so return original string unchanged		
    return str;
	}
}

And there you go. Simply run all returned color values by the plugin through RGBtoHex() first, and you should be good to go with all your little DOM color style manipulations! :)

Convert FireFox Color rgb(xxx,yyy,zzz) to Hex CodeUnit 26 MAY 2010

Firefox has a nasty habit of returning element background colors and colors in general in the format

rgb(xxx,yyy,zzz)

as opposed to the normal

#xxyyzz

hexadecimal format we’ve been accustomed to seeing from the likes of Internet Exlorer and the rest of its browser ilk.

Obviously this can trip up a fair bit of your otherwise nifty jQuery or plain old vanilla Javascript driven color features and as such, is definitely something that generally does have to be dealt with by your code.

Hence the following little useful Javascript function to use on any element color or background-color retrieval call:

//Helper function to convert a digit to a two column Hex representation
function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}

//Function to convert rgb() format values into normal hex values
function RGBtoHEX(str)
{
	if (str.substring(0, 3) == 'rgb') {
		var arr = str.split(",");
		var r = arr[0].replace('rgb(','').trim(), g = arr[1].trim(), b = arr[2].replace(')','').trim();
		var hex = [
			toHex(r),
			toHex(g),
			toHex(b)
		];
		return "#" + hex.join('');				
	}
	else{
		return str;
	}
}

So slapping this into your code would result in you changing your calls to look like this:

alert(RGBtoHEX($('#myelement').css('color')));

As you can see by examining the inside of RGBtoHex, it will only attempt to change the values fed into it in the rgb(xxx,yyy,zzz) format. Values like the one returned by IE (i.e. #06a660) will be returned unharmed!

Nifty and useful in other words!

How to Convert an UTF-16 File to an UTF-8 file using PHP CodeUnit 07 MAR 2010

Taking Andrew Walker’s previously mentioned handy little UTF-16 to UTF-8 string converter function, we now have in our means a particularly easy way in which to craft a simple UTF-16 to UTF-8 file converter, useful as I have found in the past for those silly little cases like when someone is spitting out Microsoft SQL Server generated CSV files (which are by default encoded in UTF-16) at you for example.

So let’s put down the code then shall we?

function utf16_to_utf8($str) {
    $c0 = ord($str[0]);
    $c1 = ord($str[1]);

    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $be = false;
    } else {
        return $str;
    }

    $str = substr($str, 2);
    $len = strlen($str);
    $dec = '';
    for ($i = 0; $i < $len; $i += 2) {
        $c = ($be) ? ord($str[$i]) << 8 | ord($str[$i + 1]) :
                ord($str[$i + 1]) << 8 | ord($str[$i]);
        if ($c >= 0x0001 && $c <= 0x007F) {
            $dec .= chr($c);
        } else if ($c > 0x07FF) {
            $dec .= chr(0xE0 | (($c >> 12) & 0x0F));
            $dec .= chr(0x80 | (($c >>  6) & 0x3F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        } else {
            $dec .= chr(0xC0 | (($c >>  6) & 0x1F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        }
    }
    return $dec;
}

function convert_file_to_utf8($csvfile) {
    $utfcheck = file_get_contents($csvfile);
    $utfcheck = utf16_to_utf8($utfcheck);
    file_put_contents($csvfile,$utfcheck);
}

To convert a file simply call the convert_file_to_utf8() function and pass to it the file path of the file you wish to convert. The function then uses the PHP function file_get_contents() to pack the input file’s contents into a string variable which is then passed to the main converter function which converts the string from UTF-16 to UTF-8 encoding if necessary. Finally, we use file_put_contents() to stuff the resulting string back into the original file, overwriting the original file contents.

Nice and simple really.

PHP: Convert a UTF-16 String to a UTF-8 String CodeUnit 05 MAR 2010

Andrew Walker crafted this handy little PHP function which can convert a UTF-16 encoded string into a more PHP-friendly UTF-8 encoded string.

The function first checks to see if the string passed to it is prefixed with a Byte Order Mark (BOM), and if the necessary BOM exists, the function continues to convert the rest of the string to its more compact UTF-8 format.

Obviously if no BOM is present, the function leaves the input string unchanged.

function utf16_to_utf8($str) {
    $c0 = ord($str[0]);
    $c1 = ord($str[1]);

    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $be = false;
    } else {
        return $str;
    }

    $str = substr($str, 2);
    $len = strlen($str);
    $dec = '';
    for ($i = 0; $i < $len; $i += 2) {
        $c = ($be) ? ord($str[$i]) << 8 | ord($str[$i + 1]) : 
                ord($str[$i + 1]) << 8 | ord($str[$i]);
        if ($c >= 0x0001 && $c <= 0x007F) {
            $dec .= chr($c);
        } else if ($c > 0x07FF) {
            $dec .= chr(0xE0 | (($c >> 12) & 0x0F));
            $dec .= chr(0x80 | (($c >>  6) & 0x3F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        } else {
            $dec .= chr(0xC0 | (($c >>  6) & 0x1F));
            $dec .= chr(0x80 | (($c >>  0) & 0x3F));
        }
    }
    return $dec;
}

Thanks Andrew, this was exactly what I was looking for! :)

Related Link: http://www.moddular.org/log/utf16-to-utf8

How to Convert a Webpage to a PDF CodeUnit 15 FEB 2010

Saving a web page to a PDF file for later offline viewing has just become a whole lot simpler thanks to the excellent pdfmyurl.com web service that aims to convert any URL you feed it into a downloadable PDF file. The application is particularly easy to use, looks good and returns some excellent results, making it the perfect tool for a beginner web user.

However, its magic doesn’t quite just end there.

Equipped with a host of settable options like layout, page size, dpi and zoom factor for example, pdfmyurl is geared towards allowing other developers to use the service either by making calls to it via an href anchor with the associated GET variables set, or even on their own servers if for instance they wanted to make use of the brilliant wgets functionality in order to rip a website down into PDF format.

For example:

wget -O opentracker.pdf "pdfmyurl.com?url=www.opentracker.net&-O=Landscape&--header-left=hello"

would result in the system generating a pdf file entitled opentracker.pdf in a landscape orientation and with a custom header text.

Particularly interesting for this system is the way it manages to keep menus and links active in the generated PDF file, meaning that should the page you saved as a PDF reference another article, you could still access that referenced article at a later stage by clicking on the link contained in the PDF file.

In other words, this whole damn system is simply put, pretty nifty! ;)

Related Link: http://www.pdfmyurl.com

Convert M4A to MP3 Music Files General Nonsense 05 MAR 2008

iTunes has been around since 2001 now and as an anti-Apple person myself, I’ve pretty much avoided it from the get go. However, I was finally forced to accept defeat, download and install the software after finding myself in possession of more and more .m4a music files.

The reason I conceded defeat and installed this admittedly rather good piece of software is because I like uniformity which means my music file compression of choice is the trusty old MP3 format. Now iTunes has the nifty feature of being able to convert between a number of different formats, including the m4a to mp3 conversion that I am interested in (in fact, iTunes 7 can currently read, write, and convert between MP3, AIFF, WAV, MPEG-4, AAC, and Apple Lossless. It can also convert unprotected WMV to MP3).

So, in order to convert your .m4a files to .mp3 files simply follow this process:

1) Go to the main menu and navigate to Edit -> Preferences. Once the preferences dialog box appears, click on the Advanced tab. Under the Advanced tab, go to the Importing sub-tab. The second dropdown box is labelled “Import Using:” and you need to set this to MP3 (or whatever other format you want to convert to). The “Settings” label allows you to adjust the quality of the generated files.

2) Once you have changed the preferences, simply navigate to the songs you wish to convert, select and right-click. You will see the “Convert Selection to MP3” option on the context menu. Select that and sit back, brew some coffee and wait for the conversion process to finish up.

Sorted. If you couldn’t follow the words completely, I’ve included to images to help you out. Simply click on them to enlarge.

iTunes1 Smaller iTunes2 Smaller
For more information on MPEG-4 Part 14, see: http://en.wikipedia.org/wiki/.m4a
For more information on iTunes, see: http://en.wikipedia.org/wiki/Itunes