Reduce HTTP Request with Data URI in PHP

Saturday, February 25, 2012

A part of website optimization technique is Reduce no of HTTP Request when user attempt to open our Web page from our website. HTTP Request count is an important factor for Traffic worthy websites to make your web pages / websites more responsive on time. In this factor of HTTP Request optimization to reduce the HTTP request count of various images in our websites by Rewriting with Data URI Scheme. Data URI is the technology which is used to Reduce and Optimize HTTP request and response.

For example If you have a gallery section in your website. Gallery images are in two Sections one is Thumbnails and another one is actual images. in this case set of 5 Images will request 10 HTTP request every time the Page opens. in this case we can use Data URI with PHP to reduce this HTTP request 0, Data URI will cheat our server and retrieve the image data as plain code along with our standard HTML code.

Here is the PHP function to Generate Data URI scheme for your actual image from server to Client.
Handling Data URI in  PHP is involves the encoding function base64_encode also the standard GD Image functions to manipulate image processing.

Generate data URI function
// Funtion to prepare Data URI:
// @ parm: Image filepath, Image Size
// Return : data_uri string
function generate_data_uri($filename,$width=0,$height=0) 
 // Get Image Header Type
      $image_info = getimagesize($filename);
      $image_type = $image_info[2];

 // Check the Size is Specified
 if($width!=0 and $height!=0)
      if( $image_type == IMAGETYPE_JPEG ) {
         $image = imagecreatefromjpeg($filename);
      } elseif( $image_type == IMAGETYPE_GIF ) {
         $image = imagecreatefromgif($filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
         $image = imagecreatefrompng($filename);
   imagealphablending($image, true);


 //Exploe with x and get Width Height
      $new_image = imagecreatetruecolor($width, $height);
  imagealphablending($new_image, false);
  imagesavealpha($new_image, true);     
      imagecopyresampled($new_image, $image, 0, 0, 0, 0, $width, $height, imagesx($image),imagesy($image));
      $image = $new_image; 
      if( $image_type == IMAGETYPE_JPEG ) {
      } elseif( $image_type == IMAGETYPE_GIF ) {
      } elseif( $image_type == IMAGETYPE_PNG ) {
 $base64 = base64_encode($content); 
 return "data:$image_type;base64,$base64";

<img src="<?php echo generate_data_uri('images/butterfly.jpg',640,480);?>" alt="Butterfly">
<img src="<?php echo generate_data_uri('images/butterfly.jpg',128,98);?>" alt="Globe">

Download This Script     Data URI Live Demo    

No comments:

Post a Comment