Quantcast
Channel: Lil Josh » PHP
Viewing all articles
Browse latest Browse all 11

Resizing High Resolution (Hi-res) JPEG Images with PHP

$
0
0

I kept running into a problem when I uploaded high resolution (14MP) images and tried creating thumbnails with them. The issue turned out being the PHP script ran out of memory. So it was a simple increase to about a half gig (512MB) and the script ran perfectly. Here’s the code:

thumbnail.php?src=myImage.jpg&w=300

<?php
ini_set ( "memory_limit", "512M");
header('Content-Type:image/jpeg');
echo createThumb($_GET["src"],$_GET["w"]);


function createThumb( $path, $thumbWidth ) 
{
 
    $info = pathinfo($path);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' ) 
    {

      // load image and get image size
      $img = imagecreatefromjpeg( "{$path}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

	 

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image 
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
	  $exif = exif_read_data($_GET["src"]);
	  $orientation = $exif["Orientation"]; //6 for portrait and 1 for landscape
	  if($orientation == 6 && $width > $height) {
	  	$tmp_img = imagerotate($tmp_img, 270, 0);
	  }
      return imagejpeg($tmp_img);
  
  }
}
?>

Viewing all articles
Browse latest Browse all 11

Trending Articles