~ overflow ~

Tag: img_resizer

Image Resizing Functions (… again?!)

by z3n on Mar.27, 2010, under Coding, Tips & Hints

Problem:

Oh yeah i posted this before, but now that i finally got wordpress updates i can use a decent syntax highlighter.

The main function img_resizer, is able to resize gif, png, wbmp, bmp and jpgs with proportional or cropping resize, it’s also got a function to eventually FIX the format if the filename extension is not really the same of the format, like a jpg named as file.bmp. BMP function been taken off php man pages, i will not post author’s full email to avoid spam.

Solution:

function dwordize($str) {
	$a = ord($str[0]);
	$b = ord($str[1]);
	$c = ord($str[2]);
	return $c*256*256 + $b*256 + $a;
}

function byte3($n) {
	return chr($n & 255) . chr(($n >> 8) & 255) . chr(($n >> 16) & 255);
}
function dword($n) {
	return pack("V", $n);
}
function word($n) {
	return pack("v", $n);
}
function imagebmp(&$img, $filename = false) {
	$wid = imagesx($img);
	$hei = imagesy($img);
	$wid_pad = str_pad('', $wid % 4, "\0");

	$size = 54 + ($wid + $wid_pad) * $hei;

	//prepare & save header
	$header['identifier']		= 'BM';
	$header['file_size']		= dword($size);
	$header['reserved']			= dword(0);
	$header['bitmap_data']		= dword(54);
	$header['header_size']		= dword(40);
	$header['width']			= dword($wid);
	$header['height']			= dword($hei);
	$header['planes']			= word(1);
	$header['bits_per_pixel']	= word(24);
	$header['compression']		= dword(0);
	$header['data_size']		= dword(0);
	$header['h_resolution']		= dword(0);
	$header['v_resolution']		= dword(0);
	$header['colors']			= dword(0);
	$header['important_colors']	= dword(0);

	if ($filename) {
	    $f = fopen($filename, "wb");
	    foreach ($header AS $h) {
	    	fwrite($f, $h);
	    }

		// save pixels
		for ($y=$hei-1; $y>=0; $y--) {
			for ($x=0; $x<$wid; $x++) {
				$rgb = imagecolorat($img, $x, $y);
				fwrite($f, byte3($rgb));
			}
			fwrite($f, $wid_pad);
		}
		fclose($f);
	} else {
	    foreach ($header AS $h)
	    {
	    	echo $h;
	    }

		//save pixels
		for ($y=$hei-1; $y>=0; $y--) {
			for ($x=0; $x<$wid; $x++) {
				$rgb = imagecolorat($img, $x, $y);
				echo byte3($rgb);
			}
			echo $wid_pad;
		}
	}
}
function _ckdir($fn) {
	if (strpos($fn,"/") !== false) {
		$p=substr(substr($fn,0,strrpos($fn,"/")),0,250);
		if (!is_dir($p)) {
			mkdir($p,755,true);
		}
	}
}
function imagecreatefrombmp($p_sFile) { // by alexander at http://www.php.net/manual/en/function.imagecreatefromwbmp.php
  // Load the image into a string
  $file = fopen($p_sFile,"rb");
  $read=fread($file,10);
  while(!feof($file)&&($read<>""))
  	$read.=fread($file,1024);
  $temp=unpack("H*",$read);
  $hex=$temp[1];
  $header=substr($hex,0,108);

  // Process the header
  // Structure: http://www.fastgraph.com/help/bmp_header_format.html
  if (substr($header,0,4) == "424d") {
    // Cut it in parts of 2 bytes
    $header_parts=str_split($header,2);

    // Get the width4 bytes
    $width=hexdec($header_parts[19].$header_parts[18]);

    // Get the height4 bytes
    $height=hexdec($header_parts[23].$header_parts[22]);

    // Unset the header params
    unset($header_parts);
  }

  // Define starting X and Y
  $x=0;
  $y=1;

  // Create newimage
  $image=imagecreatetruecolor($width,$height);

  // Grab the body from the image
  $body=substr($hex,108);

  // Calculate if padding at the end-line is needed
  // Divided by two to keep overview.
  // 1 byte = 2 HEX-chars
  $body_size=(strlen($body)/2);
  $header_size=($width*$height);

  // Use end-line padding? Only when needed
  $usePadding=($body_size>($header_size*3)+4);

  // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
  // Calculate the next DWORD-position in the body
  for ($i=0;$i < $body_size;$i+=3) {
    // Calculate line-ending and padding
    if ($x >= $width) {
      // If padding needed, ignore image-padding
      // Shift i to the ending of the current 32-bit-block
      if ($usePadding)
      	$i+=$width%4;

      // Reset horizontal position
      $x=0;

      // Raise the height-position (bottom-up)
      $y++;

      // Reached the image-height? Break the for-loop
      if ($y > $height)
      	break;
    }

    // Calculation of the RGB-pixel (defined as BGR in image-data)
    // Define $i_pos as absolute position in the body
    $i_pos=$i*2;
    $r=hexdec($body[$i_pos+4].$body[$i_pos+5]);
    $g=hexdec($body[$i_pos+2].$body[$i_pos+3]);
    $b=hexdec($body[$i_pos].$body[$i_pos+1]);

    // Calculate and draw the pixel
    $color=imagecolorallocate($image,$r,$g,$b);
    imagesetpixel($image,$x,$height-$y,$color);

    // Raise the horizontal position
    $x++;
  }

  // Unset the body / free the memory
  unset($body);

  // Return image-object
  return $image;
}
function img_force($src,$quality,$w,$h,$saveas,$nocrop,$force) {
	foreach (array("jpg","gif","png") as $x) { // will skip bmp formats
		if ($x != $force) {
			if (img_resizer($src,$quality,$w,$h,$saveas,$nocrop,$x)) {
				return 1;
				break;
			}
		}
	}
	return 0;
}
function img_resizer($src,$quality,$w,$h,$saveas,$nocrop=0,$force=0) { /* v2.72 with auto crop, no crop, automatic file type detection when avalible (requires exif library) */

	if (!is_file($src)) { _o("Source is not a file.");return 0; }
	if (!is_readable($src)) { _o("Can't read: ".$src);return 0; }
	if ((file_exists($saveas)) && (!is_writeable($saveas))) { _o("Can't write to: ".$saveas);return 0; }

	$r=1;

	if (function_exists('exif_imagetype')) { // automatic filetype detection
  	$e=exif_imagetype($src);
  	if ($e == IMAGETYPE_JPEG) {
  		if (!$OldImage=@ImageCreateFromJpeg($src)) { $r=0; }
  	} elseif ($e == IMAGETYPE_GIF) {
  		if (!$OldImage=@ImageCreateFromGif($src)) { $r=0; }
  	} elseif ($e == IMAGETYPE_BMP) { // custom
  		if (!$OldImage=@ImageCreateFrombmp($src)) { $r=0; }
  	} elseif ($e == IMAGETYPE_WBMP) {
  		if (!$OldImage=@ImageCreateFromwbmp($src)) { $r=0; }
  	} elseif ($e == IMAGETYPE_PNG) {
  		if (!$OldImage=@ImageCreateFromPng($src)) { $r=0; }
  	} else {
  		_o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
  	}
	} else { // filename based filetype detection, might be subject to incorrect file extensions, resulting on a error, which when enabled will fall into a try and error `force` mode
  	$e=($force == "0") ? strtolower(substr($src,strrpos($src,".")+1)) : $force;
  	if (($e == "jpg") || ($e == "jpeg")) {
  		if (!$OldImage=@ImageCreateFromJpeg($src)) { $r=0; }
  	} elseif ($e == "gif") {
  		if (!$OldImage=@ImageCreateFromGif($src)) { $r=0; }
  	} elseif ($e == "bmp") { // this is NOT wbmp
  		if (!$OldImage=@ImageCreateFrombmp($src)) { $r=0; }
  	} elseif ($e == "png") {
  		if (!$OldImage=@ImageCreateFromPng($src)) { $r=0; }
  	} else {
  		_o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
  	}
	}

	if ($r) {
		list($width,$height)=getimagesize($src);
		// check if ratios match
		$_ratio=array($width/$height,$w/$h);
		if ($_ratio[0] != $_ratio[1]) { // ratio don't match
			if ($nocrop) { // since we can't crop we will need to do image on a different height/width
    		$hx = (100 / ($width / $w)) * .01;
    		$hx = @round ($height * $hx);

    		$wx = (100 / ($height / $h)) * .01;
    		$wx = @round ($width * $wx);

    		if ($hx < $h) {
    			$h = (100 / ($width / $w)) * .01;
    			$h = @round ($height * $h);
    		} else {
    			$w = (100 / ($height / $h)) * .01;
    			$w = @round ($width * $w);
    		}
			} else { // crop image
  			// find the right scale to use
  			$_scale=min((float)($width/$w),(float)($height/$h));

  			// coords to crop
  			$cropX=(float)($width-($_scale*$w));
  			$cropY=(float)($height-($_scale*$h));

  			// cropped image size
  			$cropW=(float)($width-$cropX);
  			$cropH=(float)($height-$cropY);

  			$crop=ImageCreateTrueColor($cropW,$cropH);
  			ImageCopy($crop,$OldImage,0,0,(int)($cropX/2),(int)($cropY/2),$cropW,$cropH); // crop the middle part of the image to fit the thumbnail's proportions
			}
		}

		// do the thumbnail
		$NewThumb=ImageCreateTrueColor($w,$h);
		if (isset($crop)) { // been cropped
			ImageCopyResampled($NewThumb,$crop,0,0,0,0,$w,$h,$cropW,$cropH);
			ImageDestroy($crop);
		} else { // ratio match, regular resize
			ImageCopyResampled($NewThumb,$OldImage,0,0,0,0,$w,$h,$width,$height);
		}
		_ckdir($saveas);
		ImageJpeg($NewThumb,$saveas,$quality);
		ImageDestroy($NewThumb);
		ImageDestroy($OldImage);
	} elseif (($force == "0") && (!function_exists('exif_imagetype'))) {
		$r=img_force($src,$quality,$w,$h,$saveas,$nocrop,$e);
	}
	return $r;
}

See how nice it looks with the syntax highligher? :P

Updates:

100407 – Added imagebmp function to save as bmp;

1 Comment :, , , , , , , , more...

Ultimate PHP Resize Function

by z3n on Aug.15, 2009, under Coding

In the last few days I’ve been developing some new stuff that required my old img_resizer php function to be refurbished, I also found a issue with wBMP not being the same as BMP format.

Apart from that i got some extra file checking and the ability of recognizing the file format independent of the extension (this will only work with exif extension, which when not enabled will fall back to a try and error little loop).

There’s also some new stuff added, when you don’t want to automatically crop an `out of ratio` resized image you can enable the $nocrop option which will resize the image to the right ratio without cropping or stretching it.

So this is the v2.7, not sure if it will be the last one, but so far it’s the ultimate.

// (c) z3n – R1V2.7@090815 – www.overflow.biz – z3n666@gmail.com
  1.  
  2. function _o($x) { echo $x."’n"; }
  3.  
  4. function _ckdir($fn) {
  5.  if (strpos($fn,"/") !== false) {
  6.   $p=substr(substr($fn,0,strrpos($fn,"/")),0,250);
  7.   if (!is_dir($p)) {
  8.    mkdir($p,755,true);
  9.   }
  10.  }
  11. }
  12. function imagecreatefrombmp($p_sFile) { // by alexander@alexauto.nl at http://www.php.net/manual/en/function.imagecreatefromwbmp.php
  13.   // Load the image into a string
  14.   $file = fopen($p_sFile,"rb");
  15.   $read=fread($file,10);
  16.   while(!feof($file)&amp;&amp;($read&lt;&gt;""))
  17.    $read.=fread($file,1024);
  18.   $temp=unpack("H*",$read);
  19.   $hex=$temp[1];
  20.   $header=substr($hex,0,108);
  21.  
  22.   // Process the header
  23.   // Structure: http://www.fastgraph.com/help/bmp_header_format.html
  24.   if (substr($header,0,4) == "424d") {
  25.     // Cut it in parts of 2 bytes
  26.     $header_parts=str_split($header,2);
  27.  
  28.     // Get the width4 bytes
  29.     $width=hexdec($header_parts[19].$header_parts[18]);
  30.  
  31.     // Get the height4 bytes
  32.     $height=hexdec($header_parts[23].$header_parts[22]);
  33.  
  34.     // Unset the header params
  35.     unset($header_parts);
  36.   }
  37.  
  38.   // Define starting X and Y
  39.   $x=0;
  40.   $y=1;
  41.  
  42.   // Create newimage
  43.   $image=imagecreatetruecolor($width,$height);
  44.  
  45.   // Grab the body from the image
  46.   $body=substr($hex,108);
  47.  
  48.   // Calculate if padding at the end-line is needed
  49.   // Divided by two to keep overview.
  50.   // 1 byte = 2 HEX-chars
  51.   $body_size=(strlen($body)/2);
  52.   $header_size=($width*$height);
  53.  
  54.   // Use end-line padding? Only when needed
  55.   $usePadding=($body_size&gt;($header_size*3)+4);
  56.  
  57.   // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption
  58.   // Calculate the next DWORD-position in the body
  59.   for ($i=0;$i&lt;$body_size;$i+=3) {
  60.     // Calculate line-ending and padding
  61.     if ($x&gt;=$width) {
  62.       // If padding needed, ignore image-padding
  63.       // Shift i to the ending of the current 32-bit-block
  64.       if ($usePadding)
  65.        $i+=$width%4;
  66.  
  67.       // Reset horizontal position
  68.       $x=0;
  69.  
  70.       // Raise the height-position (bottom-up)
  71.       $y++;
  72.  
  73.       // Reached the image-height? Break the for-loop
  74.       if ($y &gt; $height)
  75.        break;
  76.     }
  77.  
  78.     // Calculation of the RGB-pixel (defined as BGR in image-data)
  79.     // Define $i_pos as absolute position in the body
  80.     $i_pos=$i*2;
  81.     $r=hexdec($body[$i_pos+4].$body[$i_pos+5]);
  82.     $g=hexdec($body[$i_pos+2].$body[$i_pos+3]);
  83.     $b=hexdec($body[$i_pos].$body[$i_pos+1]);
  84.  
  85.     // Calculate and draw the pixel
  86.     $color=imagecolorallocate($image,$r,$g,$b);
  87.     imagesetpixel($image,$x,$height-$y,$color);
  88.  
  89.     // Raise the horizontal position
  90.     $x++;
  91.   }
  92.  
  93.   // Unset the body / free the memory
  94.   unset($body);
  95.  
  96.   // Return image-object
  97.   return $image;
  98. }
  99. function img_force($src,$quality,$w,$h,$saveas,$nocrop,$force) {
  100.  foreach (array("jpg","gif","png") as $x) { // will skip bmp formats
  101.   if ($x != $force) {
  102.    if (img_resizer($src,$quality,$w,$h,$saveas,$nocrop,$x)) {
  103.     return 1;
  104.     break;
  105.    }
  106.   }
  107.  }
  108.  return 0;
  109. }
  110. function img_resizer($src,$quality,$w,$h,$saveas,$nocrop=0,$force=0) { /* v2.71 with auto crop, no crop, automatic file type detection when avalible (requires exif library) */
  111.  
  112.  if (!is_file($src)) { _o("Source is not a file.");return 0; }
  113.  if (!is_readable($src)) { _o("Can't read: ".$src);return 0; }
  114.  if ((file_exists($saveas)) && (!is_writeable($saveas))) { _o("Can't write to: ".$saveas);return 0; }
  115.  
  116.  $r=1;
  117.  
  118.  if (function_exists('exif_imagetype')) { // automatic filetype detection
  119.    $e=exif_imagetype($src);
  120.    if ($e == IMAGETYPE_JPEG) {
  121.     if (!$OldImage=@ImageCreateFromJpeg($src)) { $r=0; }
  122.    } elseif ($e == IMAGETYPE_GIF) {
  123.     if (!$OldImage=@ImageCreateFromGif($src)) { $r=0; }
  124.    } elseif ($e == IMAGETYPE_BMP) { // custom
  125.     if (!$OldImage=@ImageCreateFrombmp($src)) { $r=0; }
  126.    } elseif ($e == IMAGETYPE_WBMP) {
  127.     if (!$OldImage=@ImageCreateFromwbmp($src)) { $r=0; }
  128.    } elseif ($e == IMAGETYPE_PNG) {
  129.     if (!$OldImage=@ImageCreateFromPng($src)) { $r=0; }
  130.    } else {
  131.     _o("Not a Valid Image! (".$e.") — ".$src);$r=0;
  132.    }
  133.  } else { // filename based filetype detection, might be subject to incorrect file extensions, resulting on a error, which when enabled will fall into a try and error `force` mode
  134.    $e=($force == "0") ? strtolower(substr($src,strrpos($src,".")+1)) : $force;
  135.    if (($e == "jpg") || ($e == "jpeg")) {
  136.     if (!$OldImage=@ImageCreateFromJpeg($src)) { $r=0; }
  137.    } elseif ($e == "gif") {
  138.     if (!$OldImage=@ImageCreateFromGif($src)) { $r=0; }
  139.    } elseif ($e == "bmp") { // this is NOT wbmp
  140.     if (!$OldImage=@ImageCreateFrombmp($src)) { $r=0; }
  141.    } elseif ($e == "png") {
  142.     if (!$OldImage=@ImageCreateFromPng($src)) { $r=0; }
  143.    } else {
  144.     _o("Not a Valid Image! (".$e.") — ".$src);$r=0;
  145.    }
  146.  }
  147.  
  148.  if ($r) {
  149.   list($width,$height)=getimagesize($src);
  150.   // check if ratios match
  151.   $_ratio=array($width/$height,$w/$h);
  152.   if ($_ratio[0] != $_ratio[1]) { // ratio don't match
  153.    if ($nocrop) { // since we can't crop we will need to do image on a different height/width
  154.       $hx = (100 / ($width / $w)) * .01;
  155.       $hx = @round ($height * $hx);
  156.  
  157.       $wx = (100 / ($height / $h)) * .01;
  158.       $wx = @round ($width * $wx);
  159.  
  160.       if ($hx &lt; $h) {
  161.        $h = (100 / ($width / $w)) * .01;
  162.        $h = @round ($height * $h);
  163.       } else {
  164.        $w = (100 / ($height / $h)) * .01;
  165.        $w = @round ($width * $w);
  166.       }
  167.    } else { // crop image
  168.      // find the right scale to use
  169.      $_scale=min((float)($width/$w),(float)($height/$h));
  170.  
  171.      // coords to crop
  172.      $cropX=(float)($width-($_scale*$w));
  173.      $cropY=(float)($height-($_scale*$h));
  174.  
  175.      // cropped image size
  176.      $cropW=(float)($width-$cropX);
  177.      $cropH=(float)($height-$cropY);
  178.  
  179.      $crop=ImageCreateTrueColor($cropW,$cropH);
  180.      ImageCopy($crop,$OldImage,0,0,(int)($cropX/2),(int)($cropY/2),$cropW,$cropH); // crop the middle part of the image to fit the thumbnail's proportions
  181.    }
  182.   }
  183.  
  184.   // do the thumbnail
  185.   $NewThumb=ImageCreateTrueColor($w,$h);
  186.   if (isset($crop)) { // been cropped
  187.    ImageCopyResampled($NewThumb,$crop,0,0,0,0,$w,$h,$cropW,$cropH);
  188.    ImageDestroy($crop);
  189.   } else { // ratio match, regular resize
  190.    ImageCopyResampled($NewThumb,$OldImage,0,0,0,0,$w,$h,$width,$height);
  191.   }
  192.   _ckdir($saveas);
  193.   ImageJpeg($NewThumb,$saveas,$quality);
  194.   ImageDestroy($NewThumb);
  195.   ImageDestroy($OldImage);
  196.  } elseif (($force == "0") &amp;&amp; (!function_exists('exif_imagetype'))) {
  197.   $r=img_force($src,$quality,$w,$h,$saveas,$nocrop,$e);
  198.  }
  199.  return $r;
  200. }
Leave a Comment :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!