Last updated on July 31st, 2016 at 11:13 am

Image optimization is very important for any website. Most of eCommerce websites use no of technique to make there site  load fast. In this post i am going to share some useful code which help you to optmise you site speed and decrease your page size and page load time. Now before we start code you need to have some basic knowledge about .htaccess , and also about PHP GD library.  If you know about both then this post is very easy for you to understand.

 

Demo

Code:

Step 1. Create a directory inside your localhost.

Step 2. Now use any of text editor you like and create a file and paste below code

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?air=$1 [L,QSA]

# secure htaccess file
<Files .htaccess>
 order allow,deny
 Deny from all
 Satisfy All
</Files>

In above code we can enable Apache rewrite mode and get all request on url to index page simply we rewrite our url and whatever request over the url we get that in our index.php . And at end we prevent direct access to our .htaccess file by denying all.

Step 3. Now create index file in same directory where you put your .htaccess file.

Step 4. Now create a new file in which we create a class which help to crop image.

<?php
class pixar{
	protected $id;
	protected $pid;
	protected $pnm; 
	protected $psrc;
	protected $x;
	protected $y;
	
	function __construct($photoSrc=null, $width=null, $height=null){
		register_shutdown_function(array(&$this, '__destruct'));
		$this->psrc = $photoSrc;
		$this->x = $width;
		$this->y = $height;
		// Height of image org
		list($ox, $oy) = @getimagesize($this->psrc);	// Orignal Size of imae
		$this->width = $ox;
		$this->height = $oy;
	}
	function resize(){
		
		// *** Get optimal width and height - based on $option
		$optionArray = $this->getDimensions($this->x, $this->y, "crop");
		
		$this->x  = $optionArray['optimalWidth'];
		$this->y = $optionArray['optimalHeight'];
		$newPix = imagecreatetruecolor($this->x, $this->y) or die('Cannot Initialize new GD image stream');
		switch(strtolower(substr(strrchr($this->psrc, '.'), 1))):
			case 'jpg':
			case 'jpeg':
				$srcImg = imagecreatefromjpeg($this->psrc);
				$imageWrt = 'imagejpeg';
				$image_quality = 100;
			break;
			case 'gif':
				$srcImg = @imagecreatefromgif($this->psrc);
				$imageWrt = 'imagegif';
				$image_quality = null;
			break;
			case 'png':
				@imagecolortransparent($newPix, @imagecolorallocate($newPix, 0, 0, 0));
				@imagealphablending($newPix, false);
				@imagesavealpha($newPix, true);
				$srcImg = @imagecreatefrompng($this->psrc);
				$imageWrt = 'imagepng';
				$image_quality = 9;
			break;
			default:
				$srcImg = null;
			break;	
		endswitch;
		// Make image
		$make = imagecopyresampled($newPix, $srcImg, 0, 0, 0, 0, $this->x, $this->y, $this->width, $this->height);
		switch(substr($imageWrt, 5)):
			case 'jpeg':
				$mime = 'image/jpeg';
			break;
			case 'png':
				$mime = 'image/png';
			break;
		endswitch;
		// Free up memory (imagedestroy does not delete files):
		header('Content-Type: '.$mime);// defining the image type to be shown in browser window
	/* 	header('Cache-Control: no-cache');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); */		
		
		$imageWrt($newPix, null, $image_quality);
        imagedestroy($newPix);
	}
	private function getDimensions($newWidth, $newHeight, $option)
		{
		   switch($option)
			{
				case 'exact':
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
				break;
				case 'portrait':
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
				break;
				case 'landscape':
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				break;
				case 'auto':
					$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
				break;
				case 'crop':
					$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
				break;
			}
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}
	private function getSizeByFixedHeight($newHeight)
		{
			$ratio = $this->width / $this->height;
			$newWidth = $newHeight * $ratio;
			return $newWidth;
		}
	private function getSizeByFixedWidth($newWidth)
		{
			$ratio = $this->height / $this->width;
			$newHeight = $newWidth * $ratio;
			return $newHeight;
		}
	private function getSizeByAuto($newWidth, $newHeight)
		{
			if ($this->height < $this->width)
			// *** Image to be resized is wider (landscape)
			{
				$optimalWidth = $newWidth;
				$optimalHeight= $this->getSizeByFixedWidth($newWidth);
			}
			elseif ($this->height > $this->width)
			// *** Image to be resized is taller (portrait)
			{
				$optimalWidth = $this->getSizeByFixedHeight($newHeight);
				$optimalHeight= $newHeight;
			}
			else
			// *** Image to be resizerd is a square
			{
				if ($newHeight < $newWidth) {
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
				} else if ($newHeight > $newWidth) {
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
				} else {
					// *** Sqaure being resized to a square
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
				}
			}
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}
	private function getOptimalCrop($newWidth, $newHeight)
		{
			$heightRatio = $this->height / $newHeight;
			$widthRatio  = $this->width /  $newWidth;
			if ($heightRatio < $widthRatio) {
				$optimalRatio = $heightRatio;
			} else {
				$optimalRatio = $widthRatio;
			}
			$optimalHeight = $this->height / $optimalRatio;
			$optimalWidth  = $this->width  / $optimalRatio;
			return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
		}
	function __destruct(){
		return true;
	}
}

Above code is very easy to understand there some method in it which get size of image and some option according which you can crop your image.

Step 5. Now open index.php where we can call above class and crop image this also prevent your images directory from direct access.

<?php
require_once('pix.min.php');
$q = explode('/', $_REQUEST['air']);
$hw = $q[0];		// H X W requested
$photosrc = $q[1];      // Image
/* Extract Height width */
$Rx = substr($hw, 1, strpos($hw, '-') - 1);
$Ry = substr($hw, strpos($hw, '-') + 2, strlen($hw));
$loc = "<path of your image>";
	
/* Make call to resize image */
$re = new pixar($loc.$photosrc, $Rx, $Ry);
$re->resize();

All done, now code is ready to use

USE: it is very easy to use, you can call image like this with new dimension

http://localhost/folder_name/w290-h292/myimage.jpg

Now above your contain dimensions for image inside w(Width) and h(Height) and after that the name of image which exists inside your folder.

Hope this code is helpful to you. 🙂