Solved

php create image on foreach loop

Posted on 2013-05-21
6
543 Views
Last Modified: 2013-05-21
Hi,

i have the following code which works my uploading a photo to a directory. the script will then compare it against an thumbnail directory. if there is no thumbnail it creates one. it is all done by comparing the names. i cannot get it to work properly. the foreach loop works when there is no if statements within it. the if statements are done so it can support muliple formats.

how should i configure this to work
<?php
// Turn off all error reporting
error_reporting(0);
	
	
//SCAN THE FOLDER AND CREATE THUMBNAILS
	//BASED ON THE $DIRECTORY VALUE SET ON THE INDIVIDUAL PAGES
	//ALLOW ONLY CERTAIN IMAGE TYPES
	$files = glob("{$directory}*.{jpg,gif,png,jpeg}", GLOB_BRACE); //GIVES US THE ENTIRE LOCATION TO THE FILE 
	 
	//REMOVE THE ENDING OF THE IMAGE TO MAKE A DESRIPTION
	$file_types= array(".png",".jpeg",".jpg",".gif"); //match the allowable file types
	
	//RECONFIGURE THE NAME TO REMOVE THE FULL PATH AND THE EXTENSION OF THE FILES
	//REMOVE THE ENTIRE LENGTH OF THE FILE LOCATION AND GET JUST THE FILE NAMES
	$short_names = str_replace($directory,"",$files);
	 
//DETERMINE IF YOU WANT TO CREATE THUMBNAILS - SET ON INDIVIDUAL PAGES
	if($thumbs ===TRUE){
							
		//SET THE LOCATION OF THE THUMBNAILS BASED OFF OF THE DIRECTORY SET ON INDIVIDUAL PAGES
		$thumb_directory= $directory."thumbnail/";
		
		//CHECKS TO MAKE SURE THE THUMBDIRECTORY EXISTS IF NOT CREATE IT
		if(is_dir($thumb_directory)!==TRUE){
			mkdir($thumb_directory,0755);
		}
		
		//GET THE FILES FROM THUMBNAIL DIRECTORY
		$tb_files = glob("{$thumb_directory}*.{jpg,gif,png,jpeg}", GLOB_BRACE); //GIVES US THE ENTIRE LOCATION TO THE FILE 
		 
		//RECONFIGURE THE NAME TO REMOVE THE FULL PATH AND THE EXTENSION OF THE FILES
		//REMOVE THE ENTIRE LENGTH OF THE FILE LOCATION AND GET JUST THE FILE NAMES
		$tb_names = str_replace($thumb_directory,"",$tb_files);
		//REMOVE THE THUMBNAIL PREFIX
		$tb_prefix="tb_";
		$tb_short_names =str_replace($tb_prefix,"",$tb_names);

		//COMPARE THE THUMBS DIRECTORY TO CHECK IF IT HAS THE SAME INFORMATION--BASED ON THE SAME NAMES
		$images_difference= array_diff($short_names, $tb_short_names);
		 
		//IF THERE ARE DIFFERENCES IN THE ARRAYS MAKE A THUMB 
			foreach($images_difference as $differences){
				 
				//RENAME THE THUMB
				$rename_thumb = $tb_prefix.$differences;
				 
				//CREATE THE NEW IMAGE VARIABLE
				$new_image =$directory.$differences;
				 
				//CONFIGURE THE THUMBNAILS

				$new_height=$thumb_height;
				$new_width=$thumb_width;
				
				//GET ORIGNINAL IMAGE INFORMATION
				list($width, $height) = getimagesize($new_image);
						
				$thumb = imagecreatetruecolor($new_width, $new_height);
				
				//FIGURE OUT THE EXTENSION OF THE FILE
				$preg = pathinfo($differences, PATHINFO_EXTENSION);
				 
				//CREATE JPEG IMAGES
				if($preg == "jpg" || $preg == "jpeg"){

						$source = imagecreatefromjpeg($new_image);
						
						//RESIZE THE IMAGE
						imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						imagejpeg($thumb, $thumb_directory.$rename_thumb, 100);
						
					echo "created:".$rename_thumb."PLEASE REFRESH"."<BR/>";
				}elseif($preg == "png"){
				   //CREATE PNG IMAGES

						  $source = imagecreatefrompng($new_image);
						  
						  //RESIZE THE IMAGE
						  imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
						  imagepng($thumb, $thumb_directory.$rename_thumb, 100);
						  echo "created:".$rename_thumb."PLEASE REFRESH"."<BR/>";
				}elseif($preg == "gif"){
					//CREATE GIF IMAGE

							$source = imagecreatefromgif($new_image);
							
							//RESIZE THE IMAGE
							imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
							imagegif($thumb, $thumb_directory.$rename_thumb, 100);
							echo "created:".$rename_thumb."PLEASE REFRESH"."<BR/>";
							
				}else{
					//THE FILE IS NOT AN SUPPORTED IMAGE	
						echo "The file is not supported:".$new_image."<br/>";
					  
				}
		  }
	}

?>

Open in new window

0
Comment
Question by:M. Jayme Nagy
  • 3
  • 2
6 Comments
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
Comment Utility
if($preg == "jpg" || $preg == "jpeg"){

Should be

if($preg['extension'] == "jpg" || $preg['extension'] == "jpeg"){
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
same for the other if statements with $preg  change to $preg['extension']

Refer to this link for info on how to use pathinfo

http://www.php.net/manual/en/function.pathinfo.php
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
Comment Utility
If I am understanding the description correctly (not the code - TLDR) the program will upload an image file, then it will look for a thumbnail of the same name, and if one does not exist, it will create the thumbnail.  If that is really the logic, it seems enormously counterintuitive.  What if I uploaded an image file, then I changed the picture in the image file and uploaded it again.  Would I be stuck with the thumbnail from the original upload?  Why not (unilaterally) create the thumbnail on each upload?  Compared to the time it takes to upload a file, creating a thumbnail will not even be noticeable.

Since you're already using imageCreateTrueColor(), get rid of imageCopyResized() and use imageCopyResampled() instead.  You will get much better output!

On line 3 change that to error_reporting(E_ALL).  If there are errors, correct them in the code rather than suppressing them.  The problem with error suppression is that you do not know what errors your script encountered and suppressed.  Better to know than not know.  You can write a custom error handler if you want to deal with the errors in a non-standard way.  You can log the errors without displaying the errors to the client browser.  Almost any solution is better than suppression.

Here is my teaching example showing how to upload an image file and make a thumbnail.  You might consider adding GIF support, if there is anybody still using GIF files, but that would only be a few lines of code.

<?php // RAY_upload_and_thumbnail.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}


// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'png'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>" . PHP_EOL;
    }
    ?>
    <br/>Thumbnail Dimensions:
    <br/>Width <input name="w" />
    <br/>Height <input name="h" />
    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT TO UPLOAD THE FILS
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>" . PHP_EOL;

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));

        // USE THIS FOR WRITING ON THE SERVER
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // USE THIS FOR WRITING THE THUMBNAIL ON THE SERVER
        $my_new_tnail
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . 'tn_'
        . $f_name
        . '.png'
        ;

        // USE THIS FOR PREPARING A URL LINK OR CALLING PHP FUNCTIONS
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // USE THIS FOR PREPARING A URL LINK OR CALLING PHP FUNCTIONS
        $my_tnail
        = $uploads
        . DIRECTORY_SEPARATOR
        . 'tn_'
        . $f_name
        . '.png'
        ;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists" . PHP_EOL;;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
        // IF NO UPLOAD, DO NOT OVERWRITE ANY EXISTING THUMBNAIL
        else
        {
            die();
        }




        // RESIZE AN IMAGE TO FIT INSIDE A DEFINED TRANSPARENT SPACE
        // MAN PAGE: http://php.net/manual/en/ref.image.php

        // ACQUIRE THE DIMENSIONS - MAY NEED SOME SANITY TESTS?
        $thumb_w   = $_POST["w"];
        $thumb_h   = $_POST["h"];

        // CREATE THE THUMBNAIL IMAGE RESOURCE AND FILL IN TRANSPARENT
        $thumb = imageCreateTrueColor($thumb_w, $thumb_h);
        imageSaveAlpha($thumb, TRUE);
        $empty = imageColorAllocateAlpha($thumb,0,0,0,127);
        imageFill($thumb, 0, 0, $empty);

        // GET ORIGINAL IMAGE DIMENSIONS
        $array = getImageSize($my_file);
        if ($array)
        {
            list($image_w, $image_h) = $array;
        }
        else
        {
            die("NO IMAGE $my_file");
        }

        // ACQUIRE THE ORIGINAL IMAGE
        $image_ext = trim(strtoupper(end(explode('.', $my_file))));
        switch(strtoupper($image_ext))
        {
            case 'JPG' :
            case 'JPEG' :
                $image = imagecreatefromjpeg($my_file);
                break;

            case 'PNG' :
                $image = imagecreatefrompng($my_file);
                break;

            default : trigger_error("UNKNOWN IMAGE TYPE: $my_file", E_USER_ERROR);
        }

        // GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS
        $ratio_w = ($thumb_w / $image_w);
        $ratio_h = ($thumb_h / $image_h);
        $ratio   = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;

        // COMPUTE THUMBNAIL IMAGE DIMENSIONS
        $thumb_w_resize = $image_w * $ratio;
        $thumb_h_resize = $image_h * $ratio;

        // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
        $thumb_w_offset = ($thumb_w - $thumb_w_resize) / 2.0;
        $thumb_h_offset = ($thumb_h - $thumb_h_resize) / 2.0;

        // COPY THE IMAGE TO THE CENTER OF THE THUMBNAIL
        imageCopyResampled
        ( $thumb
        , $image
        , $thumb_w_offset
        , $thumb_h_offset
        , 0
        , 0
        , $thumb_w_resize
        , $thumb_h_resize
        , $image_w
        , $image_h
        )
        ;

        // (OPTIONAL) SHOW THE NEW THUMB IMAGE DIRECTLY IN BROWSER
        // header('Content-type: image/png');
        // imagePng($thumb);

        // WRITE THE THUMBNAIL TO DISK
        imagePng($thumb, $my_new_tnail);

        // RELEASE THE MEMORY USED BY THE IMAGE RESOURCES
        imageDestroy($thumb);
        imageDestroy($image);

        // CREATE AN IMAGE LINK FOR THE BROWSER
        echo '<br/><a target="_blank" href="' . $my_tnail . '">See the Thumb ' . $my_tnail . '</a>' . PHP_EOL;

    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

Best of luck with your project, ~Ray
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 6

Author Closing Comment

by:M. Jayme Nagy
Comment Utility
it was actually the php5.ini and the memory limit but both were excellent help
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The memory limit may be an issue if your script creates many instances of an image resource without freeing the resource.
http://php.net/manual/en/function.imagedestroy.php
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
awsome - thanks for the points - not that I deserved them - did not see the param in pathinfo to return the extension which sort of makes my post ... wrong!

Thanks anyway
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now