Base64

May 01, 2006 00:26

Simple one this time: Generation of Base64 and data: URLs. With a little hacking, you can embed little (dynamically-generated? hmmmm) images and stuff directly into your layout using this, no hosting needed.



# -----------------------------------------------------------------------------
# S2 Base64 routines v0.01 - 04/30/2006
# Copyright (c) 2006 Patrick Walton but freely redistributable
# -----------------------------------------------------------------------------

function BSFEncodeBase64(int[] data) : string
{
var string mapString =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var string[] map;
var int i = 0;
foreach var string ch ($mapString) {
$map[$i] = $ch;
$i++;
}

var string result = "";
var int val = 0;

$i = 0;
foreach var int octet ($data) {
if ($i == 0) { # 000000 00
$val = $octet / 4;
$result = $result + $map[$val];
$val = $octet % 4;
$i++;
} elseif ($i == 1) { # 001111 1111
$val = $val * 16 + $octet / 16;
$result = $result + $map[$val];
$val = $octet % 16;
$i++;
} else { # 111122 222222
$val = $val * 4 + $octet / 64;
$result = $result + $map[$val];
$val = $octet % 64;
$result = $result + $map[$val];
$i = 0;
}
}

if ($i == 1) { # one input byte remaining
$val = $val * 16;
$result = $result + $map[$val] + "==";
} elseif ($i == 2) { # two input bytes remaining
$val = $val * 4;
$result = $result + $map[$val] + "=";
}

return $result;
}

function BSFGenerateDataURL(int[] data, string mimeType) : string
{
return "data:" + $mimeType + ";base64," + BSFEncodeBase64($data);
}

# -- End of Base64 package ----------------------------------------------------

string functions

Previous post Next post
Up