2016-06-20 2 views
0

저는 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 ([email protected]_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 ([email protected]_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(); 

} 



?> 
+0

시도한 내용, 효과가없는 내용 및 최종 결과를 원하는 내용에 대한 정보를 조금 더 제공 할 수 있습니까? –

+0

@ F. 답장을 보내 주셔서 감사합니다. 위의 코드는 모든 화면 비율의 이미지를 내 서버 폴더 'uploads'에 업로드 할 수있게합니다. 업로드 할 때 정사각형이 아닌 이미지 (1 : 1)를 사각형으로 자르려면 필요합니다. 나는이 같은 몇 가지 축소판 자습서를 사용하여 시도 : http://stackoverflow.com/questions/27094895/create-square-11-thumbnail-in-php하지만 어떤 행운을 가지고 있지 않다 – BernieHm

답변

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 
} 

파일이 모든 요구 사항과 일치하면 서버에 업로드 할 수 있습니다. 물론, 스크립트를 편집하여 필요에 맞게 편집 할 수는 있지만 기본적인 생각입니다!

도움이 되었기를 바랍니다. :-) 당신은 어떤 질문이 있다면, 그냥 코멘트에 남겨주세요!

+0

안녕하세요 @ Cairo Grgurovic 그러나 이것에 대해 감사드립니다. 그것을 얻으려면 참조하십시오, 나는 자르기에 관한 섹션을 가져 와서 tmp 이름에 대한 참조가 거기에 있었는지 확인하고 내 코드에 두었습니다. 아무 것도 업로드하지 않겠습니까? – BernieHm

+0

내 코드는 위의 데스크톱에서 작동하지만 모바일에서는 작동하지 않습니다. - 모바일에서 작동하도록하려면 아무 것도 추가 할 필요가 있는지/다른 것을 할 필요가 있는지 궁금합니다. – BernieHm

+0

G'day, @BernieHm! 스위치 함수를 포함하고''// upload file to server''를 실제'move_uploaded_file' 함수 e.t.c로 바꾸 었습니까? –

관련 문제