Base64 is an encoding format that represent binary data. Google new feature instant previews are in text format, here Google requesting images(screen shots) are in string format to reduce server load time. In this post I will show you how to make images to strings with PHP.
Live Demo
Google instant previews please take a look at this screen casting.
Youtube link click here
PHP images to strings
PHP terminology there is a function called base64_encode().
<?php
$img_src = "image/sample.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>
$img_src = "image/sample.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>
More Information
When you should use base64 for images
What is the advantage of converting images to strings, just to hide the actual image name and path, or anything else ?
ReplyDeleteHi, its really nice ..
ReplyDeletei've aware bout this new feature on google for 3 last day :)
Thanks
@Dskanth
ReplyDeleteIf your webpage contains 50 images, the page sending 50 HTTP requests to server.
nice work !!!
ReplyDeleteSo surely fetching the images via ajax, or another method is feasible, but does that minimize server requests ?
ReplyDeleteOnly problem with this is, how do you cache those images to the browser?
ReplyDeleteGoogle is using this method for years. I remember I've seen this before on google search years ago, and I said wtf is this :D
ReplyDeleteGood post Srinivas.. Thanks
ReplyDeleteI think that advantage is in speed of loading images. Also I compared this image from 9lessions, in tutorial about "Blog Design with CSS and HTML", authors used same image. See differences in size between image blog_css_seo.png and img line.
ReplyDeleteResult is: 166kb for blog_css_seo.png and 48kb for img line.
Really nice. Will search for a practical use for this in my upcoming app.
ReplyDeleteNot a PHP programmer, but surely you have to fopen() the file in binary mode?
ReplyDeleteThat's what the online docs suggest: "If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters."
http://php.net/manual/en/function.fopen.php
Base64 images cannot be cached. The ONLY use you can really give to this is serve static or generated files (Gzipped!) with future ahead expire headers!! This is key.
ReplyDeleteThis way, with one HTTP GET you will fetch BOTH images and content.
Awesome blog Srinivas! Thanks for your hard work :)
I do not understand about the script, but somepeople say like this foro "Base64 Encoding for Images" with PHP...
ReplyDelete<?php
$img = imagecreatefromstring(base64_decode($string));
if($img != false)
{
imagejpeg($img, '/path/to/new/image.jpg');
}
?>
Heres for javascript "http://www.onicos.com/staff/iz/amuse/javascript/expert/base64.txt"
may be useful, salam \m/
Is in it strange that in the year 2010 having all those broadband networks we discuss 50 kb image?!?!
ReplyDeleteamazing to know. thanks again
ReplyDeleteAccording to my view.
ReplyDeleteByteArray - Decode a Base64 string to a binary data.
Dim ByteArray
Set ByteArray = CreateObject("ScriptUtils.ByteArray")
ByteArray.Base64 = "UHV0IHNvbWUgY2hhcmFjdGVycyB0by"
Wscript.Echo "Source data:" & vbCrLf & _
ByteArray.String
Man u ROCK ! btw we can just store the code in database and delete the picture from our server? it works?
ReplyDeleteI would like to point out this may be slower and requires more complicated code to use with images stored in a external source (On each page load)...
ReplyDeleteThis method doesn't work in IE for example. (at least for your live demo)
ReplyDeleteI think the best solution to reduce the number of http requests is to use sprite images.
What are the advantages of this encoding. I think HTTP request will send at each image is loading. Is it for hiding the path of the image? But we can find the image by using the firebug.
ReplyDeleteIs there any way to rewrite the path of the image? Anyway I really like this encoding :)
Arun Krishnan
http://www.configpixel.com
How can I use the base64 images with css?
ReplyDeletein CSS we have "background-image" but how to work with base64!
I want to use base64 with css coz my header and footer images are large in size and i want to load them as page loads!
Krishnan,
ReplyDeleteYou can have php generate the image on your base directory and have absolutly no link to that image since its left to php to generate it.
nice work..!!!
ReplyDeleteDear Sir,
ReplyDeleteCan you transfer the code in Javascript? I'm getting a little bit messy about the codes because in the client side, it is always browser dependent.
thank you for the code.......
ReplyDeletethat's really good
not working with 3rd party image link
ReplyDelete';
?>
Nice! Finally one that just worked and I could see why
ReplyDeletehi i have been following your page for years. it is great. i have a real estate website where i actually save the image url in mysql and pictures on my hosting. the question is should i just save them as text instead of images?
ReplyDeletethe second question is should i keeep the current settings and show images as text when page loads?
Thanks Srinivas, this post was really usefull for me
ReplyDeletehow encoded image reload script
ReplyDeletehow base64 url image in reload every 5 second script help me
ReplyDelete@Praful
ReplyDeleteYou can make the javascript to load the image every 5 sec.
setInterval(funtion(){
//Your Code
}, 5000);
Here is my hard coded php script.
ReplyDeletefunctions.php
'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
// images
'png' => 'image/png',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
'swf' => 'application/x-shockwave-flash',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'ogv' => 'video/ogg',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
);
$ext = substr($file, strrpos($file, '.') + 1);
if (key_exists($ext, $types)) return $types[$ext];
return "unknown";
}
}
function imageEncode64($file){
$type = getFileType($file);
$data = file_get_contents($file);
$base64 = '<'.'img src="data:' . $type . ';base64,' . base64_encode($data) . '">';
return $base64;
}
?>
index.php
Hope I can help you out.
Use this
ReplyDeletefunction imageEncode64($file){
$type = getFileType($file);
$data = file_get_contents($file);
$base64 = 'data:' . $type . ';base64,' . base64_encode($data);
return $base64;
}
simple and effective
nice work..
ReplyDeletehow do i decode base64 images
ReplyDeleteLarge file( 1MB -2MB ) upload fails !!
ReplyDeletegreat post!
ReplyDeletehow do I get binary data for .svg image file & how to show image for this image type?
ReplyDeleteI tried but not working...
you can try this free online service to encode base64 to image online.
ReplyDeletehi your code is totally correct but i am not able to understand how can u display the encode image becoz after encode image get encrypted right?
ReplyDeleteCan it speed up the website?
ReplyDelete