Covert GIF code to GIF image or output to file?

154 views Asked by At

I'm not exactly sure how to word this so apologies if the title is misleading. I'm using UPS's web service to create a shipping label, this is returned as a GIF, but not as an image, instead as a long code:

R0lGODdheAUgA+cAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09....... (etc)

My question is how do I use this to get an actual GIF image? preferably to output to file, and using either JavaScript or PHP.

Thanks in advance!

2

There are 2 answers

0
Sverri M. Olsen On BEST ANSWER

The string looks like base64-encoded data. Assuming it is, in fact, an image then you can decode it like this:

$encodedGif = 'R0lGODdheAUgA+cAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBw...';
$decodedGif = base64_decode($encodedGif, true);
if ($decodedGif === false) {
    die('Data has been corrupted. Unable to decode.');
}

Once you have the decoded data you can e.g. save it to a file:

$file = 'image.gif';
if ( ! file_put_contents($file, $decodedGif)) {
    die('Saving image did not work!');
}

Or you can output it to a browser as a GIF image:

header('Content-Type: image/gif');
die($decodedGif);
4
sbrbot On

The code that outputs this content (this is binary content of GIF image) has to announce in header to server that this content represents a GIF image (otherwise the server does not know how to represent this content). So your PHP code in header statement should define something like:

header('Content-Type: image/gif');

Look at http://php.net/manual/en/function.imagegif.php