【问题标题】:Using php to crop an image into a square when uploading to a server上传到服务器时使用php将图像裁剪为正方形
【发布时间】:2016-06-23 21:55:47
【问题描述】:

我是 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();

}



?>

【问题讨论】:

  • 您能否提供更多信息,说明您尝试过的方法、无效的方法以及您想要的最终结果是什么?
  • @F.StephenQ 感谢您的回复。上面的当前代码允许将所有纵横比的图像上传到我的服务器文件夹“上传”。我需要它来裁剪任何不是正方形(1:1)的图像,使其在上传时变成正方形。我尝试过使用一些这样的缩略图教程:stackoverflow.com/questions/27094895/… 但没有任何运气

标签: php


【解决方案1】:

您可以使用原生 php imagecrop 函数使用数组来削减图像大小。相当简单。

如果图像是正方形,它不会做任何事情。但是,如果图像的“宽度”大于“高度”,则会将宽度裁剪为高度并将图像居中,反之亦然。

$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
}

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

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

【讨论】:

  • 嗨@Caelan Grgurovic 谢谢你,但是我看不到让它工作,我把关于裁剪的部分放在我的代码中,确保对 tmp 名称的引用也在那里,并且它不会上传任何东西?
  • 我上面的代码可以在桌面上运行,但不能在移动设备上运行 - 我想知道我是否需要添加任何东西/做任何不同的事情才能让它在移动设备上运行?
  • 祝你好运,@BernieHm!您是否确保包含开关功能并将// upload file to server 替换为实际的move_uploaded_file 功能等?
  • @BernieHm hmm :/ 当我在 iPhone 上测试它时它对我有用吗?连接或读/写权限可能有问题?
  • 嗨@Caelan Grgurovic,再次感谢您的回复-这听起来很愚蠢,但我不确定如何将上传功能集成到您上面的代码中,如果您愿意的话我有一个将文件重命名为其unix时间戳的函数,这也将如何集成?非常感谢!
猜你喜欢
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多