1

i'm a php newbie and still trying to get to grips with the language. I need to crop the images i'm uploading into squares using php. Here is my current code to upload the images (which is working fine):

<?php


error_reporting(0); 



    $sUploadDirectory   = 'uploads/';

    $aFileTypesAllowed  = array('image/jpeg', 'image/gif', 'image/png');
    $aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');


    $aJSExtensions      = 'new Array("gif", "png", "jpg", "jpeg")';


    $bImagesOnly = true;

    $iMaxFileSize = 102400;




if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {


    $bSuccess   = true;
    $sErrorMsg  = 'Your image was successfully uploaded.';


    if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false || 
        !in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {

        $bSuccess   = false;
        $sErrorMsg  = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);


    } else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {

        $bSuccess   = false;
        $sErrorMsg  = 'The image is invalid or corrupt. Please select another.';


    } else if ($_FILES['myFile']['size'] > $iMaxFileSize) {

        $bSuccess   = false;
        $sErrorMsg  = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';


    } else {



        if (!@move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $_FILES['myFile']['name'])) {
            $bSuccess   = false;
            $sErrorMsg  = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
        }

    }




    print   '<html>' .
                '<head>' .
                    '<script type="text/javascript">' .
                        'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $_FILES['myFile']['name'] . '\');' .
                    '</script>' .
                '</head>' .
                '<body></body>' .
            '</html>';


    die();

}
?>

I've tried adding this after the last argument checking the file size, it works on desktop, however doesn't on mobile when you use the 'take photo' option, which is an essential option in my design:

  //*********************
 //crop image into sqaure
//**********************



// Original image
$filename = $_FILES['myFile']['tmp_name'];

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);


// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - 320;
$top = $current_height / 2 - 320;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 640;
$crop_height = 640;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width,      
$current_height);
imagejpeg($canvas, $filename, 100);


  //*********************
 //crop image into sqaure
//**********************

I'm wondering if I have coded this poorly causing it not to work, If any one could help i'd be very grateful! Thanks!

so this is the code that works on desktop but not on mobile, the first html entry above works on mobile and desktop.

<?php

error_reporting(0); 

$sUploadDirectory   = 'uploads/';

$aFileTypesAllowed  = array('image/jpeg', 'image/gif', 'image/png');
$aExtensionsAllowed = array('gif', 'png', 'jpg', 'jpeg');

$aJSExtensions      = 'new Array("gif", "png", "jpg", "jpeg")';

$bImagesOnly = true;
$iMaxFileSize = 4194304;

if(isset($_REQUEST['upload']) && $_REQUEST['upload'] == 'true') {

$temp = explode(".", $_FILES["myFile"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);

$bSuccess   = true;
$sErrorMsg  = 'Thanks! Your image was successfully uploaded.';

if (array_search($_FILES['myFile']['type'], $aFileTypesAllowed) === false || 
        !in_array(end(explode('.', strtolower($_FILES['myFile']['name']))), $aExtensionsAllowed)) {

        $bSuccess   = false;
        $sErrorMsg  = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);


    } else if ($bImagesOnly && !(getimagesize($_FILES['myFile']['tmp_name']))) {

        $bSuccess   = false;
        $sErrorMsg  = 'The image is invalid or corrupt. Please select another.';



    } else if ($_FILES['myFile']['size'] > $iMaxFileSize) {

        $bSuccess   = false;
        $sErrorMsg  = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';

    } else {


$filename = $_FILES['myFile']['tmp_name'];

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);


// The x and y coordinates on the original image where we
// will begin cropping the image
$left = $current_width / 2 - ($current_width / 2);
$top = $current_height / 2 - ($current_width / 2);

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $current_width;
$crop_height = $current_width;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);





        if (!@move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $newfilename)) {
            $bSuccess   = false;
            $sErrorMsg  = 'An unexpected error occurred while saving your uploaded photo. Please try again.';
        }




    }



    print   '<html>' .
                '<head>' .
                    '<script type="text/javascript">' .
                        'parent.uploadResult(' . ($bSuccess ? 'true' : 'false') . ', \'' . $sErrorMsg . '\', \'' . $sUploadDirectory . $newfilename . '\');' .
                    '</script>' .
                '</head>' .
                '<body></body>' .
            '</html>';


    die();

}



?>
BernieHm
  • 11
  • 1
  • 6
  • Could you provide a bit more information on what you've tried, what hasn't worked, and what exactly you want the end result to be? – F. Stephen Q Jun 20 '16 at 16:47
  • @F.StephenQ thanks for responding. The current code above allows images of all aspect ratios to be uploaded to my server folder 'uploads'. I need it to crop any images that are not square(1:1) to be square on upload. I have tried using a few thumbnail tutorials like this: http://stackoverflow.com/questions/27094895/create-square-11-thumbnail-in-php but not having any luck – BernieHm Jun 21 '16 at 12:44

1 Answers1

3

You can use the native PHP function imagecrop.

The following code will cut anything that is not a square (if the aspect ratio is greater or less than 1).

Of course, this is a little bit thrown together and could absolutely be a little bit more optimized, but it will do for now.

// Uploaded file temporary location
$fileTemp = $_FILES["myFile"]["tmp_name"];
// Validate the file extension. 
$fileExt = strtolower(end(explode(".", $_FILES["myFile"]["name"])));
switch($fileExt){ 
    case "jpg":
    case "jpeg":
        $image = imagecreatefromjpeg($fileTemp);
    break;
    case "png":
        $image = imagecreatefrompng($fileTemp);
    break;
    case "gif":
        $image = imagecreatefromgif($fileTemp);
    break;
    default:
        $errorMessage = "Invalid file format. Acceptable formats are: " . implode(", ", $validFileTypes);
}

// Retrieve image resolution and aspect ratio.
list($width, $height) = getimagesize($fileTemp);
$aspectRatio = $width / $height;

// Crop the image based on the provided aspect ratio.
if($aspectRatio !== 1){
    $portrait = $aspectRatio < 1;

    // This will check if the image is portrait or landscape and crop it square accordingly.
    $image = imagecrop($image, [
        "x" => $portrait ? 0 : (($width - $height) / 2),
        "y" => $portrait ? (($width - $height) / 2) : 0,
        "width"  => $portrait ? $width : $height,
        "height" => $portrait ? $width : $height
    ]);
}

// Constrain max file size.
$maxFileSize = 102400;
if($_FILES["myFile"]["size"] >= $maxFileSize){
    $errorMessage = "The file size of your property photo must not exceed " . ($maxFileSize / 1024) . "Kb. Please try again.";
}

// Send to CDN...
if(empty($errorMessage)){

}
GROVER.
  • 4,071
  • 2
  • 19
  • 66
  • Hi @Caelan Grgurovic thanks for this however I cant see to get it to work, I took the section regarding the cropping out and placed it in my code ensuring the reference to the tmp name was also there and it wouldn't upload anything? – BernieHm Jun 23 '16 at 11:33
  • my code above works on desktop but not on mobile - I was wondering if i needed to add anything / do anything different to make it work on mobile? – BernieHm Jun 23 '16 at 11:34
  • G'day, @BernieHm! Did you make sure to include the switch function and swap out the `// upload file to server` with the actual `move_uploaded_file` function e.t.c.? – GROVER. Jun 23 '16 at 11:35
  • @BernieHm hmm :/ it works for me when I test it out on my iPhone? possible problem with the connection or read / write permissions? – GROVER. Jun 23 '16 at 11:36
  • Hi @Caelan Grgurovic, thanks again for the reply - this is going to sound pretty dumb, but im not sure how to integrate the upload function into your code above, also if you'd be so kind I have a function renaming the file as its unix timestamp, how would this be integrated as well? many thanks! – BernieHm Jun 23 '16 at 11:52
  • would it just be this in your brackets? move_uploaded_file($_FILES['myFile']['tmp_name'], $sUploadDirectory . $newfilename) – BernieHm Jun 23 '16 at 11:57
  • yep! :-) exactly that – GROVER. Jun 23 '16 at 11:58
  • hi @ Caelan Grgurovic, i have added my exact code above in the question as it wouldn't fit down here, it doesnt seem to be working : - / – BernieHm Jun 23 '16 at 12:08
  • please may you send a demo file? – BernieHm Jun 23 '16 at 12:14