Looking for a very basic crop upload script

For over 3 hours now I am searching for a very basic crop/upload script where the image should go in two different folders (thumbnails and photos. What I have found so far are all classes with massive coding. Does anybody know of a very basic script or tutorial?

Thank you

Do you want to use GD or Imagemagick?

GD code I wrote a few years ago and was working then!
I would guess duplicating this line imagejpeg( $canvas, “cropped.jpg” ); with the two different paths should work.


<?php
// Crop dimensions.
$width = 100;
$height = 100;
// Set the path to the image to resize
$input_image = "House.jpg";
// Get the size of the original image into an array
$size = getimagesize( $input_image );
// Prepare canvas
$canvas = imagecreatetruecolor( $width, $height );
// Create a new image in the memory from the file
$cropped = imagecreatefromjpeg( $input_image );
// Prepare image  crop - center the crop on the image
$newwidth = $size[0] / 2;
$newheight = $size[1] / 2;
$cropLeft = ( $newwidth/2 ) - ( $width/2 );
$cropHeight = ( $newheight/2 ) - ( $height/2 );
// Generate the cropped image
imagecopyresized( $canvas, $cropped, 0,0, $cropLeft, $cropHeight, $size[0], $size[1], $newwidth, $newheight );
// Save the cropped image as cropped.jpg
imagejpeg( $canvas, "cropped.jpg" );
// Clear the memory of the tempory images
imagedestroy( $canvas );
imagedestroy( $cropped );
?> 

Imagemagick method - in this case saving 4 different images:


<?php
$cmd = " input.jpg \\( -clone 0 -thumbnail x480 -write 480_wide.jpg +delete \\)".
" \\( -clone 0 -thumbnail x250 -write 250_wide.jpg +delete \\) ".
" \\( -clone 0 -thumbnail x100 -write 100_wide.jpg +delete \\) -thumbnail 64x64! null: ";
exec("convert $cmd 64_square.jpg ");
?>

Hi Rubble. Maybe a bit stupid but I am not completely sure what you mean with the above. The paths to the folders should be …/gallery/thumbnails/ & …/gallery/photos/

Should that be:


imagejpeg( $canvas, "../gallery/thumbnails/cropped.jpg" );
imagejpeg( $canvas, "../gallery/photos/cropped.jpg" );

Thank you in advance

GD is a program currently built into php that works and people say it is safer. Imagemagick as you can see is a lot simpler, has more options but is currently an external program and people say it is not as safe.
I did forget about Imagick which is an Imagemagick API that is built into version 5+ of php. This has most of the options of Imagemagick and is supposedly safer but can be a pain to install and get working. If you are used to OOP it would probably be straight forward to you.

Basicaly they are all image editing programs.

Yes I would guess your piece of php code should work, as I understand it $canvas should be in the memory until the memory is cleared.

If you are interested you can checkout some Imagemagick, Imagick and some GD code on my website, link below.

Hi Rubble. I was just looking into some of your examples. Very impressive and I have bookmarked your site :slight_smile:
I found this example Resize image on upload:

 <?php
// If the form has been submitted do this
if ( isset( $_POST['Submit'] ) ){

// Temporary upload image name
$original_image = $_FILES['filename']['tmp_name'];

// Get the image dimensions
$size=GetImageSize( $original_image );

// Name to save the image as - in this case the same as the original
$new_image = $_FILES['filename']['name'];

// Maximum image width
$max_width = "200";

// Maximum image height
$max_height = "90";

// Resize the image and save

exec("convert $original_image -thumbnail $max_widthx$max_height $new_image");

echo "File uploaded<br>";

echo "<img src=\\"".$new_image."\\">";
}
else { ?>
<p>File to upload:</p>
<form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data"> 
<input type="file" name="filename"  />
<input type="Submit" name="Submit" value="Submit" />
</form>
<?php } ?>

It is looking very straight forward and way more compact then most classes I have seen today.Is it possibe to adjust this so two images are cropt and uploaded to the different folders? Another question is. Is it also possible to just set the height and that the width is auto?

Thank you in advance!

Thank you for the comments about my site, I hardly scratch the surface of what Imagemagick can do myself.

The code of mine you posted is quite old and should be updated. You will need to confirm you have Imagemagick installed on your server before going to far with it.
Try this code and see what result you get:


<?php
echo "<pre>";
system("convert -version");  
system("type convert"); 
echo "</pre>";
?> 

Is it possible to adjust this so two images are cropped and uploaded to the different folders? Another question is. Is it also possible to just set the height and that the width is auto?

The answer is yes to both of your questions.

Hi Rubble. I guess I am not lucky. Just tested it but I don’t get any result? Page source just gives me the <pre></pre>

You might be lucky and Imagick is working; try:


<?php  
$version = Imagick::getVersion(); 
echo "API version number: ".$version['versionNumber']."<br>"; 
echo "API version string: ".$version['versionString']."<br>"; 
 ?> 

If not you will have to use GD which is not a problem once the code is written.

This is the result.


API version number: 1576
API version string: ImageMagick 6.2.8 05/07/12 Q16 file:/usr/share/ImageMagick-6.2.8/doc/index.html

But that is on my server. I have a quick test on client server

Edit: It’s not on client server :frowning:

That’s a shame.

One of the reason the crop codes you have looked at are quite complicated is you have to give GD more settings and do more calculations.
You have to read the dimensions of the original image to get the image ratio and calculate the top left corner for the crop.

I am out of practice with it now as I have not used it for 10 years?

Hi Rubble I found the following about function with GD


<?php
 
define('THUMBNAIL_IMAGE_MAX_WIDTH', 200);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 100);

function generate_image_thumbnail($source_image_path, $thumbnail_image_path) {
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
        $thumbnail_image_width = $source_image_width;
        $thumbnail_image_height = $source_image_height;
    } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
        $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
    } else {
        $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
        $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
    imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
    imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($thumbnail_gd_image);
    return true;
}

define('UPLOADED_IMAGE_DESTINATION', '../gallery/');
define('THUMBNAIL_IMAGE_DESTINATION', '../gallery/thumbnails/');

function process_image_upload($field) {
    $temp_image_path = $_FILES[$field]['tmp_name'];
    $temp_image_name = $_FILES[$field]['name'];
    list(, , $temp_image_type) = getimagesize($temp_image_path);
    if ($temp_image_type === NULL) {
        return false;
    }
    switch ($temp_image_type) {
        case IMAGETYPE_GIF:
            break;
        case IMAGETYPE_JPEG:
            break;
        case IMAGETYPE_PNG:
            break;
        default:
            return false;
    }
    $uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
    move_uploaded_file($temp_image_path, $uploaded_image_path);
	
    $thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace('{\\\\.[^\\\\.]+$}', '.jpg', $temp_image_name);
    $result = generate_image_thumbnail($uploaded_image_path, $thumbnail_image_path);
    return $result ?  array($uploaded_image_path, $thumbnail_image_path) : false;
}


$result  = process_image_upload('Image1');

if ($result === false) {
    echo '<br>An error occurred while processing upload';
} else {
    echo '<br>Uploaded image saved as ' . $result[0];
    echo '<br>Thumbnail image saved as ' . $result[1];

}
?>

I tried to add another function for creating the photos since in this examplethe original is without cropping going into the the destination folder. So I actuallly copied generate_image_thumbnail function and basically replaced everything that was called thumbnail:


function generate_image_photo($source_image_path, $photo_image_path) {
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $photo_aspect_ratio = PHOTO_IMAGE_MAX_WIDTH / PHOTO_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= PHOTO_IMAGE_MAX_WIDTH && $source_image_height <= PHOTO_IMAGE_MAX_HEIGHT) {
        $photo_image_width = $source_image_width;
        $photo_image_height = $source_image_height;
    } elseif ($photo_aspect_ratio > $source_aspect_ratio) {
        $photo_image_width = (int) (PHOTO_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $photo_image_height = PHOTO_IMAGE_MAX_HEIGHT;
    } else {
        $photo_image_width = PHOTO_IMAGE_MAX_WIDTH;
        $photo_image_height = (int) (PHOTO_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $photo_gd_image = imagecreatetruecolor($photo_image_width, $photo_image_height);
    imagecopyresampled($photo_gd_image, $source_gd_image, 0, 0, 0, 0, $photo_image_width, $photo_image_height, $source_image_width, $source_image_height);
    imagejpeg($photo_gd_image, $photo_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($photo_gd_image);
    return true;
}

And called it the same as I called the thumbnail function. But nothing happened. Strange thing though. When I took out the generate_image_thumbnail function the photo function was working.

Do you have any idea what the reason can be?

Please can you confirm what you want to do to the photos.
Photo 1 save to …/gallery/thumbnails/cropped.jpg + crop, resize, crop and resize?
Photo 2 save to …/gallery/photos/cropped.jpg + crop, resize, crop and resize?

Hi Rubble thanks for the reply. That is indeed where I am after. And most to set a max-height for both instead of max-width and max-height.

Already all day I am looking for a very basic crop and upload script, but apperntly that doesn’t exist in PHP unless you use Imagemagick as mentioned by Rubble . For example. I am quite used to use Coldfusion. If I need to create a normal photo file and a thumbnail the following code will make this happen:


<cfset thumbnailPath 	= expandpath('../slideshow_photos/thumbnails')>
<cfset photoPath    	= expandpath('../slideshow_photos/photos')>

<cffile action="upload" filefield="fileUpload" destination="#photoPath#" nameconflict="makeunique" accept="image/*" mode="777">

<cfimage name="uploadedImage" source="#photoPath#/#file.serverFile#" >

<cfimage action="resize" width="" height="80" source="#uploadedImage#" destination="#thumbnailPath#/#file.serverFile#" overwrite="true">

<cfif uploadedImage.width gt photoWidth AND uploadedImage.height gt photoHeight>

<cfimage action="resize" width="" height="550" source="#uploadedImage#" destination="#photoPath#/#file.serverFile#" overwrite="true"/>
			
</cfif>

Where in PHP I need something like this to reach nearly the same result:


<?php

define('THUMBNAIL_IMAGE_MAX_HEIGHT', 80);
define('PHOTO_IMAGE_MAX_HEIGHT', 550);


function generate_image_thumbnail($source_image_path, $thumbnail_image_path) {
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $photo_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
        $thumbnail_image_width  = $source_image_width;
        $thumbnail_image_height = $source_image_height;
    } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
        $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
    } else {
        $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
        $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
    imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
    imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($thumbnail_gd_image);
    return true;
}

function generate_image_photo($source_image_path, $photo_image_path) {
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $photo_aspect_ratio = PHOTO_IMAGE_MAX_WIDTH / PHOTO_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= PHOTO_IMAGE_MAX_WIDTH && $source_image_height <= PHOTO_IMAGE_MAX_HEIGHT) {
        $photo_image_width  = $source_image_width;
        $photo_image_height = $source_image_height;
    } elseif ($photo_aspect_ratio > $source_aspect_ratio) {
        $photo_image_width = (int) (PHOTO_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $photo_image_height = PHOTO_IMAGE_MAX_HEIGHT;
    } else {
        $photo_image_width = PHOTO_IMAGE_MAX_WIDTH;
        $photo_image_height = (int) (PHOTO_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $photo_gd_image = imagecreatetruecolor($photo_image_width, $photo_image_height);
    imagecopyresampled($photo_gd_image, $source_gd_image, 0, 0, 0, 0, $photo_image_width, $photo_image_height, $source_image_width, $source_image_height);
    imagejpeg($photo_gd_image, $photo_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($photo_gd_image);
    return true;
}

define('UPLOADED_IMAGE_DESTINATION', '../gallery/');
define('THUMBNAIL_IMAGE_DESTINATION', '../gallery/thumbnails/');
define('PHOTO_IMAGE_DESTINATION', '../gallery/photos/');

function process_image_upload($field){
    $temp_image_path = $_FILES[$field]['tmp_name'];
    $temp_image_name = $_FILES[$field]['name'];
    list(, , $temp_image_type) = getimagesize($temp_image_path);
	
    if ($temp_image_type === NULL) {
        return false;
    }
    switch ($temp_image_type) {
        case IMAGETYPE_GIF:
            break;
        case IMAGETYPE_JPEG:
            break;
        case IMAGETYPE_PNG:
            break;
        default:
            return false;
    }
	
    $uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;
    move_uploaded_file($temp_image_path, $uploaded_image_path);
	
	$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace('{\\\\.[^\\\\.]+$}', '.jpg', $temp_image_name);
	$photo_image_path = PHOTO_IMAGE_DESTINATION . preg_replace('{\\\\.[^\\\\.]+$}', '.jpg', $temp_image_name);
	
	$res_thumbnail    = generate_image_thumbnail($uploaded_image_path, $thumbnail_image_path);
    $res_photo        = generate_image_photo($uploaded_image_path, $photo_image_path);
	
	return $res_thumbnail ? array($uploaded_image_path, $thumbnail_image_path) : false;
    return $res_photo ? array($uploaded_image_path, $photo_image_path) : false;
}

    $res_thumbnail  = process_image_upload('Image1');
    $res_photo      = process_image_upload('Image1');
	

?>

Is there really not a more simple sollution to just crop and upload an image using PHP?

This is a simple upload form and will only accept jpg files, resize them to two different heights, save into two different directories and check they were uploaded:


<?php
// If the form has been submitted do this
if ( isset( $_POST['Submit'] ) ){

// Function to resize the image
function resize( $height, $image, $new ){

// Get the image dimensions
$size = GetImageSize( $image );

// Calculate the new image dimensions to maintain the ratio
$ratio = $height/$size[1];
$max_width = $size[0]*$ratio;

// Resize the image and save
$src_img = ImageCreateFromJPEG( $image );
$resize = ImageCreateTrueColor( $max_width, $height );
ImageCopyResampled( $resize, $src_img, 0, 0, 0, 0, $max_width, $height, $size[0],$size[1] );
ImageJPEG( $resize, $new );
ImageDestroy( $resize );

// Check new file created
if ( is_readable( $new )){
echo "The file was uploaded to $new<br>";}
else echo "The file $new was not uploaded<br>";
}

// Check the file is a jpg
$fileType = exif_imagetype($_FILES['filename']['tmp_name']);
$allowed = array(IMAGETYPE_JPEG);
if (in_array($fileType, $allowed)) {

// Uploaded file
$original_image = $_FILES['filename']['tmp_name'];
$new_image =  $_FILES['filename']['name'];

// New file path/names
$thumbnail = 'th_'.$new_image;
$photo = $new_image;

// Resize and save
// Maximium height, uploaded file, new name
$photo = resize( '200', $original_image, $photo);
$thumb = resize( '100', $original_image, $thumbnail);
}

// Non jpg error
else echo "That file type is invalid";

}
else { ?>
<p>File to upload ( jpg files only ):</p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>" enctype="multipart/form-data">
<input type="file" name="filename"  />
<input type="Submit" name="Submit" value="Submit" />
</form>
<?php } ?>

Wow this looks great and quite straightforward Rubble :tup:. Just one question left about this:


// New file path/names
$thumbnail = 'th_'.$new_image;
$photo = $new_image;

Where do I set the path?

Thanks donboe; you just add the path in front of the file name:


// New file path/names
$thumbnail = 'gallery/th_'.$new_image;
$photo = 'gallery/'.$new_image;

As you can see this code is using a function so you can have more saves, alter the sizes etc.

This is great. Thank you for all your input. This was driving me insane. You made my day!!!