Base64 Encoding for Images.
Wall Script
Follow Me:
Tuesday, November 16, 2010

Base64 Encoding for Images.

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.

base64 for images

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.'" />';

?>

More Information
When you should use base64 for images
Was this article helpful?
Thanks! Your feedback helps us to improve 9lessons.info


42 comments:

  1. What is the advantage of converting images to strings, just to hide the actual image name and path, or anything else ?

    ReplyDelete
  2. Hi, its really nice ..

    i've aware bout this new feature on google for 3 last day :)

    Thanks

    ReplyDelete
  3. @Dskanth

    If your webpage contains 50 images, the page sending 50 HTTP requests to server.

    ReplyDelete
  4. So surely fetching the images via ajax, or another method is feasible, but does that minimize server requests ?

    ReplyDelete
  5. Only problem with this is, how do you cache those images to the browser?

    ReplyDelete
  6. Google 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

    ReplyDelete
  7. I 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.
    Result is: 166kb for blog_css_seo.png and 48kb for img line.

    ReplyDelete
  8. Really nice. Will search for a practical use for this in my upcoming app.

    ReplyDelete
  9. Not a PHP programmer, but surely you have to fopen() the file in binary mode?

    That'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

    ReplyDelete
  10. 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.

    This way, with one HTTP GET you will fetch BOTH images and content.

    Awesome blog Srinivas! Thanks for your hard work :)

    ReplyDelete
  11. I do not understand about the script, but somepeople say like this foro "Base64 Encoding for Images" with PHP...

    <?php

    $img = imagecreatefromstring(base64_decode($string));
    if($img != false)
    {
    imagejpeg($img, &apos;/path/to/new/image.jpg&apos;);
    }

    ?>

    Heres for javascript "http://www.onicos.com/staff/iz/amuse/javascript/expert/base64.txt"
    may be useful, salam \m/

    ReplyDelete
  12. Is in it strange that in the year 2010 having all those broadband networks we discuss 50 kb image?!?!

    ReplyDelete
  13. According to my view.
    ByteArray - 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

    ReplyDelete
  14. Man u ROCK ! btw we can just store the code in database and delete the picture from our server? it works?

    ReplyDelete
  15. I 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)...

    ReplyDelete
  16. This method doesn't work in IE for example. (at least for your live demo)

    I think the best solution to reduce the number of http requests is to use sprite images.

    ReplyDelete
  17. 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.

    Is there any way to rewrite the path of the image? Anyway I really like this encoding :)

    Arun Krishnan
    http://www.configpixel.com

    ReplyDelete
  18. How can I use the base64 images with css?
    in 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!

    ReplyDelete
  19. Krishnan,
    You 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.

    ReplyDelete
  20. Dear Sir,

    Can 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.

    ReplyDelete
  21. thank you for the code.......
    that's really good

    ReplyDelete
  22. not working with 3rd party image link

    ';

    ?>

    ReplyDelete
  23. Nice! Finally one that just worked and I could see why

    ReplyDelete
  24. hi 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?
    the second question is should i keeep the current settings and show images as text when page loads?

    ReplyDelete
  25. Thanks Srinivas, this post was really usefull for me

    ReplyDelete
  26. how base64 url image in reload every 5 second script help me

    ReplyDelete
  27. @Praful
    You can make the javascript to load the image every 5 sec.

    setInterval(funtion(){
    //Your Code
    }, 5000);

    ReplyDelete
  28. Here is my hard coded php script.

    functions.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.

    ReplyDelete
  29. Use this

    function imageEncode64($file){
    $type = getFileType($file);
    $data = file_get_contents($file);
    $base64 = 'data:' . $type . ';base64,' . base64_encode($data);
    return $base64;
    }

    simple and effective

    ReplyDelete
  30. Large file( 1MB -2MB ) upload fails !!

    ReplyDelete
  31. how do I get binary data for .svg image file & how to show image for this image type?
    I tried but not working...

    ReplyDelete
  32. hi 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?

    ReplyDelete

Make in India