2012-09-10 1 views
2

저는 PHP 놉입니다. 업로드 된 이미지를 작은 크기로 축소하는 이미지 크기 조정 스크립트를 만들려고합니다. 아래의 현재 스크립트를 사용하면 원본 이미지가 표시됩니다. 새로운 너비와 높이가 등록되어 있지 않습니다. 어떤 도움을 주셔서 감사합니다.PHP 이미지가 다른 마임 유형에 맞게 크기 조정

<?php 

    if ($_SERVER['REQUEST_METHOD']=='POST') { 
     if (isset($_FILES['image']['tmp_name'])) { 
     if ($_FILES['image']['error']==0){ 
     $new_dir = '/PHP_MySQL_Practice/uploaded/images'; 
     $fullpath = $_SERVER['DOCUMENT_ROOT'].$new_dir; 
     if(!is_dir($fullpath)) { 
      mkdir($fullpath, 0777, TRUE); 
     } 
     //get file name and type(extension) 
     $name = $_FILES['image']['name']; 
     $type = $_FILES['image']['type']; 

     //separate image name after first "dot" 
     $separated = explode(".", $name); 
     //get string before the dot which was stored as the 1st item in the separated array. 
     $first = $separated[0]; 
     //use php function pathinfo to get extension of image file 
     $ext = pathinfo($name, PATHINFO_EXTENSION); 
     //concatenate current timestamp (to avoid file overwrites) with the extracted file 'firstname' and add the extension 
     $name = time().'_'.$first.'.'.$ext; 
     $target = $fullpath.'/'.$name; 

     if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) { 

      resizeImage($target, $name); 
      echo '<img src="' . $target . '"/>'; 

     } 

    } 
    else { 

     echo 'there was an error in saving ur image file.'; 
    } 
} 
else { 

    echo 'ur image could not be uploaded.'; 
} 
    } 
    else { 
    ?> 
<form method="POST" enctype="multipart/form-data"> 
    <label>upload image: </label> 
    <input type="file" name="image" /> 
    <input type="submit" /> 
</form> 
    <?php 
    } 

    //function to resize image 
    function resizeImage($dir, $img) { 
list($src_w, $src_h) = getimagesize($dir); 
$max_w = 150; 
$max_h = 150; 
if ($src_w > $max_w) { 
    $ratio = $max_w/$src_w; 
    $new_img_w = $src_w * $ratio; 
} 
else if ($src_h > $max_h) { 
    $ratio = $max_h/$src_h; 
    $new_img_h = $src_h * $ratio; 
} 
$img_mime_type = getimagesize($dir); 
switch ($img_mime_type['mime']) { 
    case 'image/jpeg': 
    case 'image/pjpeg': 
     $src = imagecreatefromjpeg($dir); 
     return $src; 
     break; 
    case 'image/gif': 
     $src = imagecreatefromgif($dir); 
     return $src; 
     break; 
    case 'image/png': 
     $src = imagecreatefrompng($dir); 
     return $src; 
     break; 
    default: 
     return FALSE; 
     break; 
} 
$new_img = imagecreatetruecolor($new_img_w, $new_img_h); 
imagecopyresampled($new_img, $src, 0, 0, 0, 0, $new_img_w, $new_img_h, $max_w, $max_h); 
switch ($img_mime_type['mime']) { 
    case 'image/jpeg': 
    case 'image/pjpeg': 
     imagejpeg($new_img, $dir, 100); 
     break; 
    case 'image/gif': 
     imagegif($new_img, $dir); 
     break; 
    case 'image/png': 
     imagepng($new_img, $dir); 
     break; 
    default: 
     return FALSE; 
     break; 
} 

imagedestroy($src); 
imagedestroy($new_img); 
    } 
    ?> 
+0

예입니다 주어진 혀를 좀 봐, 이것이 당신이 원하는 도움이되기를 바랍니다 http://blog.webtech11.com/2012/04/21/upload-and-resize-an-image-with-php.html –

답변

3

가 일부 결함이

  1. imagegif 만 2 매개 변수 $im이있다하고 저장 위치
  2. imagepng는 압축 수준을 가지고 당신이에서 이미지, null를 저장하지 않는 0 ~ 100
  3. 9 및하지에서 imagejpeg($new_img, null, 100);$dir으로 변경해야합니다.
  4. 마지막 기능은 imagdestroy($src);이며, 잘못 입력하면여야합니다.

귀하의 switch은 다음과 같아야합니다

switch ($img_mime_type['mime']) { 
    case 'image/jpeg': 
    case 'image/pjpeg': 
     imagejpeg($new_img, $dir, 100); 
     break; 
    case 'image/gif': 
     imagegif($new_img, $dir); 
     break; 
    case 'image/png': 
     imagepng($new_img, $dir); 
     break; 
    default: 
     return FALSE; 
     break; 
} 

당신의 크기 조정 기능 : 기능 아래

function resizeImage($dir, $img) { 
    //echo $dir; die; 
    list($src_w, $src_h) = getimagesize($dir); 
    $max_w = 150; 
    $max_h = 150; 
    if ($src_w > $max_w) { 
     $ratio = $max_w/$src_w; 
     $max_w = $src_w * $ratio; 
    } 
    else if ($src_h > $max_h) { 
     $ratio = $max_h/$src_h; 
     $max_h = $src_h * $ratio; 
    } 
    $img_mime_type = getimagesize($dir); 
    $src = imagecreatefromstring(file_get_contents($dir)); 
    $new_img = imagecreatetruecolor($max_w, $max_h); 
    imagecopyresampled($new_img, $src, 0, 0, 0, 0, $max_w, $max_h, $src_w, $src_h); 
    switch ($img_mime_type['mime']) { 
     case 'image/jpeg': 
     case 'image/pjpeg': 
      imagejpeg($new_img, $dir, 100); 
      break; 
     case 'image/gif': 
      imagegif($new_img, $dir); 
      break; 
     case 'image/png': 
      imagepng($new_img, $dir); 
      break; 
     default: 
      return FALSE; 
      break; 
    } 

    imagedestroy($src); 
    imagedestroy($new_img); 
} 
+0

위에서 언급 한 변경 사항을 시도했지만 ... 여전히 아무것도 아닙니다! –

+0

전체 switch 문은'imagecreatefromstring (file_get_contents ($ dir))'로 대체 될 수 있으며, 지원되지 않는 유형 인 경우 false를 확인합니다. –

+0

@shakirahman 어떤 오류가 있습니까? display_errors를 –

0

이미지를 저장하는 것이 아니라 이미지의 내용을 출력하는 것입니다. imagejpeg의 문서를 확인하면 두 번째 인수는 이미지를 저장하려는 경로임을 알 수 있습니다. 따라서 두 번째 인수 (null)를 크기가 조정 된 이미지를 저장할 위치로 변경하십시오.

+0

좋아, 림 나는 그것을 밖으로 시험해 본다. –

0

사용이 기능을 사용해보십시오 이미지를

function image_resize($image, $maxWidth, $maxHeight = null) 
{ 
     $file = $image; 
     $file_headers = @get_headers($file); 

     //validate file not exists 
     if(isset($file_headers[0]) && strpos($file_headers[0], '404')) { 
      return; 
     } 

    $arrayUploadPath = wp_upload_dir(); 
    $fileUploadSubDir = str_replace(basename($image),'', str_replace($arrayUploadPath['baseurl'], '', $image)); 
    $fileUploadDir = $arrayUploadPath['basedir'] . $fileUploadSubDir; 

    //validate sour ce file existance 
    if(!file_exists($fileUploadDir . basename($src))) return null; 

    $fileUploadUrl = $arrayUploadPath['baseurl'] . $fileUploadSubDir; 
    $srcFileName = $fileUploadDir . basename($image); 
    $srcSize = getimagesize($srcFileName); 
    $width = $srcSize[0]; 
    $height = $srcSize[1]; 

    if(empty($maxHeight)) { 
     $size = wp_constrain_dimensions($width, $height, $maxWidth); 
     $maxHeight = $size[1]; 
    } 

    //fix for image_resize_dimensions() constraint in image_resize() function 
    if($maxHeight >= $height) $maxHeight = $height - 1; 

    $newImage = image_resize($srcFileName, $maxWidth, $maxHeight); 

    $newFileNameUrl = !empty($newImage) && !is_object($newImage) ? $fileUploadUrl . basename($newImage) : null; 

    return $newFileNameUrl; 
} 
+0

나는 그것이 작동하고 더 최적 일지 모르지만 나는 지금까지 내가 아는 것과 함께 일하려고하는 PHP를 배우려고 노력하고있다. 감사. –

0

크기를 조정할 수 ...

당신이 경우

  1. 비율로 이미지 크기를 조정 할 수있는 총 세 가지 가능성이 있기 때문에 당신이 당신의 요구 사항에 따라 높이와 너비를 전달할 수있는이 함수에 6,

    는 높이 다음으로 크기를 조정해야 할 폭보다 더 많은입니다 신장.

  2. 너비가 너비보다 크면 너비를 조정해야합니다.
  3. 높이와 너비가 모두 조정됩니다. 여기

은 ...

//first of all get Height and width of image 

function getHeight($image) { 
    $sizes = getimagesize($image); 
    $height = $sizes[1]; 
    return $height; 
} 

//You do not need to alter these functions 
function getWidth($image) { 
    $sizes = getimagesize($image); 
    $width = $sizes[0]; 
    return $width; 
} 

지금

$width = $this->getWidth($fullpath); 
    $height = $this->getHeight($fullpath); 

    $profilecroppedthumb = UPLOAD_PATH."FILENAME_WITH_EXTENSION"; 
    $fullpath = $uploadDirectory.$filename.'.'.$ext; 

     if ($width >= 500 && $height >= 500) { 
      thumb($fullpath, $profilecroppedthumb, "500", "500"); 
     } 
     elseif($width >= 500 && $height <= 500) 
     { 
      thumb($fullpath, $profilecroppedthumb, "500", ""); 
     } 
     elseif($width <= 500 && $height >= 500) 
     { 
      thumb($fullpath, $profilecroppedthumb, "", "500"); 
     } 
     else 
     { 
      $target = fopen($profilecroppedthumb, "w"); 
      fseek($temp, 0, SEEK_SET); 
      stream_copy_to_stream($temp, $target); 
      fclose($target); 
     } 
function thumb($file, $save, $width="", $height="") 
{ 
    //GD-Lib > 2.0 only! 
    //@unlink($save); 

    //get sizes else stop 

    if (!$infos = @getimagesize($file)) { 
    //echo $infos = @getimagesize($file); exit('saf'); 
     return false; 
    } 

    // keep proportions 
    $iWidth = $infos[0]; 
    $iHeight = $infos[1]; 
    $iRatioW = $width/$iWidth; 
    $iRatioH = $height/$iHeight; 


    if($height == "") { 
     if ($iRatioW < $iRatioH) { 
       $iNewW = $iWidth * $iRatioW; 
       $iNewH = $iHeight * $iRatioW; 
      } else { 
       $iNewW = $iWidth * $iRatioW; 
       $iNewH = $iHeight * $iRatioW; 
      } 
    } 
    elseif ($width == "") 
    { 
    if ($iRatioW < $iRatioH) { 
       $iNewW = $iWidth * $iRatioH; 
       $iNewH = $iHeight * $iRatioH; 
      } else { 
       $iNewW = $iWidth * $iRatioH; 
       $iNewH = $iHeight * $iRatioH; 
      } 
    } 
    else 
    { 
     if ($iRatioW < $iRatioH) { 
      $iNewW = $iWidth * $iRatioW; 
      $iNewH = $iHeight * $iRatioW; 
     } else { 

      $iNewW = $iWidth * $iRatioH; 
      $iNewH = $iHeight * $iRatioH; 


     } 
    } 
    //$iNewW = $width; 
    //$iNewH = $height; 

    //Don't resize images which are smaller than thumbs 
    if ($infos[0] < $width && $infos[1] < $height) { 
     $iNewW = $infos[0]; 
     $iNewH = $infos[1]; 
    } 

    if($infos[2] == 1) { 
     /* 
     * Image is typ gif 
     */ 
     $imgA = imagecreatefromgif($file); 
     $imgB = imagecreate($iNewW,$iNewH); 

     //keep gif transparent color if possible 
     if(function_exists('imagecolorsforindex') && function_exists('imagecolortransparent')) { 
      $transcolorindex = imagecolortransparent($imgA); 
       //transparent color exists 
       if($transcolorindex >= 0) { 
        $transcolor = imagecolorsforindex($imgA, $transcolorindex); 
        $transcolorindex = imagecolorallocate($imgB, $transcolor['red'], $transcolor['green'], $transcolor['blue']); 
        imagefill($imgB, 0, 0, $transcolorindex); 
        imagecolortransparent($imgB, $transcolorindex); 
       //fill white 
       } else { 
        $whitecolorindex = @imagecolorallocate($imgB, 255, 255, 255); 
        imagefill($imgB, 0, 0, $whitecolorindex); 
       } 
     //fill white 
     } else { 
      $whitecolorindex = imagecolorallocate($imgB, 255, 255, 255); 
      imagefill($imgB, 0, 0, $whitecolorindex); 
     } 
     imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]); 
     imagegif($imgB, $save);   

    } elseif($infos[2] == 2) { 
     /* 
     * Image is typ jpg 

     */ 
     $imgA = imagecreatefromjpeg($file); 
     $imgB = imagecreatetruecolor($iNewW,$iNewH); 
     imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]); 
     imagejpeg($imgB, $save,100); 

    } elseif($infos[2] == 3) { 
     /* 
     * Image is typ png 
     */ 
     $imgA = imagecreatefrompng($file); 
     $imgB = imagecreatetruecolor($iNewW, $iNewH); 
     imagealphablending($imgB, false); 
     imagecopyresampled($imgB, $imgA, 0, 0, 0, 0, $iNewW, $iNewH, $infos[0], $infos[1]); 
     imagesavealpha($imgB, true); 
     imagepng($imgB, $save,100); 
    } else { 
     return false; 
    } 

    return true; 
} 

희망이 도움말 (두 폭 높이) 여기에 내가 500 픽셀 함께 일하고 원하는 치수와 크기를 조정,

관련 문제