上传到服务器时使用php将图像裁剪成正方形

时间:2016-06-20 15:47:43

标签: php

我是一个php新手,仍然试图掌握这门语言。 我需要使用php裁剪我正在上传到正方形的图像。这是我当前上传图像的代码(工作正常):

<?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();

}
?>

我尝试在最后一个参数检查文件大小后添加它,它可以在桌面上运行,但是当你使用'拍照'选项时这不是在手机上,这是我设计中必不可少的选项:

  //*********************
 //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
//**********************

我想知道我是否编码不好导致它无法正常工作, 如果有人能帮助我会非常感激!谢谢!

所以这是适用于桌面但不适用于移动设备的代码,上面的第一个html条目适用于移动设备和桌面设备。

<?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();

}



?>

1 个答案:

答案 0 :(得分:2)

您可以使用本机php imagecrop函数使用数组来缩小图像大小。相当简单。

如果图像是正方形,则不会执行任何操作。但是,如果图像具有更大的宽度&#34;比高度&#34;,它会将宽度裁剪到高度并使图像居中,反之亦然。

$file       = $_FILES['myFile']['name']; // get file name
$fileext    = strtolower(end(explode('.', $file))); // get file extension
$filetmp    = $_FILES['myFile']['tmp_name']; //get file tmp name

switch ($fileext) { // check file extension using switch function
    case 'jpg':
    case 'jpeg':
        $image = imagecreatefromjpeg($filetmp);
    break;
    case 'png':
        $image = imagecreatefrompng($filetmp);
    break;
    case 'gif':
        $image = imagecreatefromgif($filetmp);
    break;
    default:
         $sErrorMsg  = 'Invalid file format. Acceptable formats are: ' . implode(', ', $aFileTypesAllowed);
}

list($w, $h) = getimagesize($filetmp); // get image resolution

if ($w < $h){ // if width is less than height, crop height using imagecrop function
    $image = imagecrop($image, array(
        "x" => 0,
        "y" => ($w - $h) / 2,
        "width" => $w,
        "height" => $w
    ));
} else if ($h < $w){ // vice versa
    $image = imagecrop($image, array(
        "x" => ($w - $h) / 2,
        "y" => 0,
        "width" => $h,
        "height" => $h
    ));
}

if($_FILES['myFile']['size'] > 102400){
    $sErrorMsg  = 'The file size of your property photo must not exceed ' . ($iMaxFileSize / 1024) . 'Kb. Please try again.';
}

if(empty($sErrorMsg){
    // upload file to server
}

如果文件符合所有要求,则可以将其上传到您的服务器。当然,您可以更改编辑脚本以满足您的需求,但这只是基本的想法!

我希望这有帮助! :-)如果您有任何疑问,请将它们留在评论中!