You need to expand on "doesn't work". Make sure error reporting is enabled:
You should also determine which is failing by determining if its image creation or the socket communication that's no good.
The one thing that jumps out immediately is this:
$im = $imagecreate(300, 100) or die ("Cannot Intialize new GD image stream");
$imagecreate isn't declared anywhere, so unless you specify
$imagecreate = 'imagecreate';
, than that will throw a fatal error.