lose jpg png image size in original dimension

0.79K views
no comments
20 Sep 2015 2:15 am

This is big storage problem in computer, mobiles and all other devices, heavy and camera images consumed too many storage and website will become heavy if heavy images used on websites

I also use my php code to lose images weight without losing dimension and quality of image

Here is I write a short tutorial and code you tell how compress it with php. I am using compress two most popular extension jpg and png.

First to set Infinity script execution otherwise script will be stopped and showing an error

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted

I have set at 2GB

set_time_limit('2024M');
ini_set('memory_limit', '2024M');

Create function I named it lose_imagweight

lose_imagweight function have four parameters first is source absolute path name with name and extension of original image, second is where you save it with absolute path name and extension, third parameter is used for quality of jpeg image and jpeg image quality start from 1 to 100 (low to high) and fourth parameter for png quality and png quality start from 0 to 9 (high to low)

function lose_imageweight($srcimage,$targetimg,$jpg_quality=70,$png_quality=9){
	$imagedetails=getimagesize($srcimage);
	$image_mime = $imagedetails['mime'];
	$is_imagesave = false;
	switch($image_mime){
		case "image/jpg":
		case "image/jpeg":
		$img = imagecreatefromjpeg($srcimage);
		$is_imagesave=imagejpeg($img,$targetimg, $jpg_quality);
		break;
		case "image/png":
		$img = imagecreatefrompng($srcimage);
		//keep transparent image
		imagealphablending($img,true);
		imagesavealpha($img,true);
		$is_imagesave = imagepng($img,$targetimg, $png_quality);
		break;
	}
	if($is_imagesave){
		return true;
	} else {
		return false;
	}
}

Set variables current path source path and target path

Create two folders 1 source folder and 2 compressed folder , copy photos image to source folder that set in $src_path and second folder in $target_path, If you want to replace with original just set as $target_path = $src_path; this overwrite the compressed images.

$current_dir = dirname(__FILE__).'/';
$src_path = $current_dir.'uncompressed_images/';
$target_path = $current_dir.'compressed_images/';

For compress images from folder

first get files with scandir php function to and run foreach loop file, define two variables $Targetpath and $SRCpath call function lose_imageweight and add file sizes difference

Note for same SRC and TARGET path

Image compressed may be shown old or new same size, but it will compressed the image, like uncompressed image size is 100005 and after compressed image size is 10005 bytes and it will shown compressed image.jpg from 100005 to 100005 bytes because this is happens to me may this is a bug or logical issue

$dir_files = scandir($src_path);

foreach($dir_files as $fileindex=>$filepath){
	if($filepath=='.' || $filepath=='..'){
		continue;
		//leave loop if back directory path in loop.
	}
	$TARpath = $target_path.$filepath;
	$ABSpath = $src_path.$filepath;
	$old_filesize = filesize($ABSpath);
	if(lose_imageweight($ABSpath,$TARpath,85,9)){
		$new_filesize = filesize($TARpath);
		echo $filepath.' compressed from '.$old_filesize.' to '.$new_filesize.' bytes
<hr />

';
	}
}

Compress images when user upload files via html browse file.

First create html form with browse files button and enctype=”multipart/form-data”


<form method="post" enctype="multipart/form-data" />
	<input type="file" multiple="" name="multifiles[]" title="add multifiles"/>
	<input type="submit" value="upload and compress" />
</form>

Second check if $_FILES[‘multifiles’] run loop and get file name and file tmp_name and pass both in lose_imageweight function

if(is_array($_FILES['multifiles']) && !empty($_FILES['multifiles'])){
  $filesdata = $_FILES['multifiles'];
  for($fileinc=0;$fileinc<count($filesdata['name']); $fileinc++){
    $filename = $filesdata['name'][$fileinc];
    $filesrc = $filesdata['tmp_name'][$fileinc];
    $old_filesize =$filesdata['size'][$fileinc];
    $ABS_filepath = $target_path.$filename;
    if(move_uploaded_file($filesrc,$ABS_filepath)){
      if(lose_imageweight($ABS_filepath,$ABS_filepath,85,9)){
        $new_filesize = filesize($ABS_filepath);
        echo $filename.' compressed from '.$old_filesize.' to '.$new_filesize.' bytes
<hr />

';
      }
    }
  }
}

Bulk images compression with recursive complete folder directories

Create function scandir mean scan directories with a single parameter the current absolute path, this function is recursive it will scan nested directories, but in bulk images compression imagetargetpath must be same.

function scandirs($path=null){
	$files_dirs = scandir($path);
	foreach($files_dirs as $dirinex=>$filespath){
		if($filespath =='.' || $filespath=='..'){
			continue;
		}
		$abs_path = $path.$filespath;
		if(is_dir($abs_path)){
			scandirs($abs_path);
		} else {
			lose_imageweight($abs_path,$abs_path,85,9);
		}
	}
}

Define the starting path where you wish to start recursive bulk images compression

$current_dir = dirname(__FILE__).'/';
$src_path = $current_dir.'uncompressed_images/';
$dir_files = scandir($src_path);

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>