Mmm, I looked into this a bit more, and if you already have a base 64 encoded string (you cannot copy, type or paste non base 64 encoded image data into a textarea anyway), no PHP is required, and for GIF (I tested with a 1 x 1 transparent GIF image), it doesn't seem to matter what file format you use, but I've included that in the code anyway:
Code:
<!DOCTYPE html>
<html>
<head>
<title>String to Image</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
img {border: 1px solid black;background-color:red;padding:1px;width:100px;height:100px;}
</style>
</head>
<body>
<img id="image" width="100" height="100" alt="missing image" title=""><br>
<form id="form" action="#">
<textarea name="imagetext" cols="50" rows="5" wrap="off">R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==</textarea><br>
Choose Format:<br>
GIF: <input type="radio" name="format" value="gif"><br>
JPEG: <input type="radio" name="format" value="jpeg"><br>
PNG: <input type="radio" name="format" value="png"><br>
Show at Native Dimensions (check for yes): <input type="checkbox" name="native" value="native"><br>
Show with no Background (check for yes): <input type="checkbox" name="nobg" value="nobg"><br>
<input type="submit" value="Go">
</form>
<script type="text/javascript">
document.getElementById('form').onsubmit = function(e){
e = e || event;
e.preventDefault && e.preventDefault();
e.returnValue = false;
var format, formats = this.elements.format, i = formats.length, image = document.getElementById('image');
if(this.elements.native.checked){
image.style.width = image.style.height = 'auto';
} else {image.style.width = image.style.height = '';}
if(this.elements.nobg.checked){
image.style.background = 'none';
} else {image.style.background = '';}
while(--i > -1){
if(formats[i].checked){
format = formats[i].value;
break;
}
}
image.src = 'data:image/' + (format || 'jpeg') + ';base64,' + this.elements.imagetext.value;
}
</script>
</body>
</html>
When the page loads you will see a red square with the alt text (missing image) in it. After submitting (the Go button), the text will disappear because the transparent GIF image is there. You will still see the red though, because the image is transparent, except in IE 8 and less which don't allow background for images. The image still loads though, and will show the page background (white).
I later also tried this with a large JPEG image and it failed, but with small and medium sized ones it worked fine.
Ah, but then I discovered that the problem with the larger image was that I hadn't gotten the entire base 64 encoded data for it. Once I was able to do that, it worked. If you're interested in how to get the base 64 encoded data from an image, let me know. My method requires PHP 5 or greater (but could be rewritten for PHP 4) and for images not on the server, requires permission to open remote files be set in PHP, and it can be preformed via AJAX, for which I used jQuery.
Bookmarks