2013-01-10 2 views
1

매개 변수에 따라 이미지를 다른 방식으로 처리하는 함수가 생성되었습니다. 함수에 약간 설명 할 주석이 있습니다.jpg를 PHP로 투명 png로 저장하기

모든 기능은 jpg 이미지를 가져 와서 png로 저장할 때 예외적으로 작동합니다. 방금 확인했는데 imagepng()을 사용했지만 .jpg 확장명으로 저장해도 이미지의 크기는 올바르게 조정되지만 .jpg 확장명으로 표시됩니다. 그러나 동일한 .jpg 이미지를 업로드하고 imagepng()을 사용하고 .png 확장자로 저장하면 .png 확장자를 가진 png 형식의 예상 너비와 높이 이미지를 얻을 수 있습니다. 전체 이미지가 100 % 투명하지만 상단 왼쪽 구석에 1 픽셀 x 1 픽셀의 검정색 픽셀이 있습니다.

누군가가 이것을보고 내가 누락 된 부분을 볼 수 있으면 감사하겠습니다. 나는 1x1xxx가 imagefill()을 위해 사용하는 지점에서 나오고 있다고 믿는다. 그러나 나는 왜 그런지 이해하지 못한다. 이미지의 나머지 부분과 마찬가지로 투명하게 채워야합니다.

if(!function_exists("upload")){ 
    //$image = $image file name 
    //$width = intended width of resized image, if 0 it will proportion to height, overrides proportion 
    //$height = intended width of resized image, if 0 it will proportion to width, overrides proportion 
    //$proportion = 2,1,0; 
    //------ 2 = Preserve proportions while adding a border to fill width and height 
    //------ 1 = retain proportion to fit within both given width and height 
    //------ 0 = disregard proportions and resize to the exact width and height 
    function upload($image, $width, $height, $proportion){ 
     // IS GD HERE? 

     $gdv = get_gd_info(); 

     if (!$gdv){ 
      return FALSE; 
     } 

     // GET AN IMAGE THING 

     $ext = trim(strtolower(end(explode('.', $image)))); 

     list($imageX, $imageY, $type) = getimagesize($image); //gets information about new server image 

     // GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS 
     $ratio_w = ($width/$imageX); 
     $ratio_h = ($height/$imageY); 
     $ratio = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;  

     if($width == 0){ 

      if($imageY > $height){ 
       $newHeight = $height; 
       $newWidth = ($height/$imageY) * $imageX;  
      }else{ 
       $newHeight = $imageY; 
       $newWidth = $imageX;  
      } 

      $width = $newWidth; 
      $height = $newHeight; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = 0; 
      $fromMidY = 0; 

     }elseif($height == 0){ 

      if ($imageX > $width){ 
       $newWidth = $width; 
       $newHeight = ($width/$imageX) * $imageY; 
      }else{ 
       $newHeight = $imageY; 
       $newWidth = $imageX;  
      } 

      $width = $newWidth; 
      $height = $newHeight; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = 0; 
      $fromMidY = 0; 

     }elseif($proportion == 2){ 

      // COMPUTE THUMBNAIL IMAGE DIMENSIONS 
      $newWidth = $imageX * $ratio; 
      $newHeight = $imageY * $ratio; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = ($width - $newWidth)/2.0; 
      $fromMidY = ($height - $newHeight)/2.0; 

     }elseif($proportion == 1){ 

      if ($imageX > $width){ 
       $newHeight = ($width/$imageX) * $imageY; 
       $newWidth = $width; 
      } 
      if ($imageY > $height){ 
       $newHeight = $height; 
       $newWidth = ($height/$imageY) * $imageX; 
      } 

      $fromMidY = 0; 
      $fromMidX = 0; 

     }elseif($proportion == 0){ 

      $newWidth = $width; 
      $newHeight = $height; 

      $fromMidY = 0; 
      $fromMidX = 0;   
     } 

     switch(strtoupper($ext)) 
     { 
      case 'JPG' : 
      case 'JPEG' : 
       $source = imagecreatefromjpeg($image); 
       break; 

      case 'PNG' : 
       $source = imagecreatefrompng($image); 

       break; 

      default : die("UNKNOWN IMAGE TYPE: $image"); 
     } 

     // WHICH FUNCTIONS CAN RESIZE/RESAMPLE THE IMAGE? 
     if ($gdv >= 2) 
     { 

      // IF GD IS AT LEVEL 2 OR ABOVE 
      $target = imagecreatetruecolor($width, $height); 
      $color = imagecolorallocatealpha($target, 0, 0, 0, 127); 

      imagefill($target, 0, 0, $color); 

      imagesavealpha($target, TRUE); 


      imagecopyresampled ($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY); 

     } 
     else 
     { 
      // IF GD IS AT A LOWER REVISION LEVEL 
      $target = imagecreate($width, $height); 
      imagesavealpha($target, TRUE); 
       $empty = imagecolorallocatealpha($thumb,0x00,0x00,0x00,127); 
       imagefill($target, 0, 0, $empty); 
      imagecopyresized($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY); 
     } 

     // SHARPEN THE PIC 
     $sharpenMatrix = array 
     (array(-1.2, -1, -1.2) 
     , array(-1, 20, -1) 
     , array(-1.2, -1, -1.2) 
     ) 
     ; 
     $divisor = array_sum(array_map('array_sum', $sharpenMatrix)); 
     $offset = 0; 
     imageconvolution($target, $sharpenMatrix, $divisor, $offset); 

     if(imagepng($target, $image,9)){ 

      imagedestroy($target); 
     }else{ 

     } 

     return $image; 
    } 
} 

편집 : 1 : 여기

내 기능입니다 나는 내가 .JPG 이미지를 업로드하고 있음을 주목해야 추측 (예를 : 100 픽셀 X 200 픽셀) 및 .png를로 변환 (예 : 400 픽셀 X 200 픽셀). 목적지의 중심에 완벽하게 맞도록 이미지의 비율을 유지합니다. 따라서 중앙에 내 이미지가있는 400px X 200px .png와 투명해야하는 왼쪽과 오른쪽의 100px가 있습니다. 이 방법은 단색을 채우지 않고 슬라이더에 잘 맞습니다. 따라서 내 함수 호출에 대한 예는 upload($image, 400, 200, 2)입니다.

+0

한 설명을 위해 사용할 계획 좋은 hex2rgb/rgb2hex 기능이 있습니다 마음에 온다 : 당신이 JPEG를 업로드하고 PNG로 변환하는 경우, 당신은 더 투명한 픽셀이 없습니다. 그러나 이미지의 전체가 왼쪽 위 모퉁이의 픽셀을 투명하게 처리한다고 가정합니다. 내가 뭘 놓치고 있니? – halfer

+0

[여기]보세요 (http://stackoverflow.com/questions/7610128/use-php-to-convert-jpegs-to-transparent-png) –

+0

@halfer 나는 왜 내가 명확하게 도울 수 있도록 내 질문을 편집했다. 투명 픽셀을 가져야합니다. 처음부터 추가해야한다고 생각합니다. –

답변

0

문제가 무엇인지 알아 냈습니다. imagecreatefromjpeg 또는 imagecreatefrompng 중 어느 것을 사용해야하는지 결정하는 코드 부분은 mime 형식이 아니라 전달 된 이미지의 확장자가 잘못 처리됩니다.

switch($type) 
     { 
      case '2' : 
       $source = imagecreatefromjpeg($image); 
       break; 
      case '3' : 
       $source = imagecreatefrompng($image); 
       break; 
      default : die("UNKNOWN IMAGE TYPE: $image"); 
     } 

$type이 라인에서 오는 내가

list($imageX, $imageY, $type) = getimagesize($image); 

그래서 모두 함께 기능이 거기에 있었다 여기서 :

if(!function_exists("upload")){ 
    //$image = $image file name 
    //$width = intended width of resized image, if 0 it will proportion to height, overrides proportion 
    //$height = intended width of resized image, if 0 it will proportion to width, overrides proportion 
    //$proportion = 2,1,0; 
    //------ 2 = Preserve proportions while adding a border to fill width and height 
    //------ 1 = retain proportion to fit within both given width and height 
    //------ 0 = disregard proportions and resize to the exact width and height 


    function upload($image, $width, $height, $proportion){ 
     // IS GD HERE? 

     $gdv = get_gd_info(); 

     if (!$gdv){ 
      return FALSE; 
     } 

     // GET AN IMAGE THING 

     $ext = trim(strtolower(end(explode('.', $image)))); 

     list($imageX, $imageY, $type) = getimagesize($image); //gets information about new server image 

     // GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS 
     $ratio_w = ($width/$imageX); 
     $ratio_h = ($height/$imageY); 
     $ratio = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;  

     if($width == 0){ 

      if($imageY > $height){ 
       $newHeight = $height; 
       $newWidth = ($height/$imageY) * $imageX;  
      }else{ 
       $newHeight = $imageY; 
       $newWidth = $imageX;  
      } 

      $width = $newWidth; 
      $height = $newHeight; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = 0; 
      $fromMidY = 0; 

     }elseif($height == 0){ 

      if ($imageX > $width){ 
       $newWidth = $width; 
       $newHeight = ($width/$imageX) * $imageY; 
      }else{ 
       $newHeight = $imageY; 
       $newWidth = $imageX;  
      } 

      $width = $newWidth; 
      $height = $newHeight; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = 0; 
      $fromMidY = 0; 

     }elseif($proportion == 2){ 

      // COMPUTE THUMBNAIL IMAGE DIMENSIONS 
      $newWidth = $imageX * $ratio; 
      $newHeight = $imageY * $ratio; 

      // COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS 
      $fromMidX = ($width - $newWidth)/2.0; 
      $fromMidY = ($height - $newHeight)/2.0; 

     }elseif($proportion == 1){ 

      if ($imageX > $width){ 
       $newHeight = ($width/$imageX) * $imageY; 
       $newWidth = $width; 
      } 
      if ($imageY > $height){ 
       $newHeight = $height; 
       $newWidth = ($height/$imageY) * $imageX; 
      } 

      $fromMidY = 0; 
      $fromMidX = 0; 

     }elseif($proportion == 0){ 

      $newWidth = $width; 
      $newHeight = $height; 

      $fromMidY = 0; 
      $fromMidX = 0;   
     } 

     switch($type) 
     { 
      case '2' : 
       $source = imagecreatefromjpeg($image); 
       break; 
      case '3' : 
       $source = imagecreatefrompng($image); 
       break; 
      default : die("UNKNOWN IMAGE TYPE: $image"); 
     } 

     // WHICH FUNCTIONS CAN RESIZE/RESAMPLE THE IMAGE? 
     if ($gdv >= 2) 
     { 

      // IF GD IS AT LEVEL 2 OR ABOVE 
      $target = imagecreatetruecolor($width, $height); 
      $color = imagecolorallocatealpha($target, 0, 0, 0, 127); 
      imagefill($target, 0, 0, $color); 
      imagesavealpha($target, TRUE); 
      imagecopyresampled ($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY); 

     } 
     else 
     { 
      // IF GD IS AT A LOWER REVISION LEVEL 
      $target = imagecreate($width, $height); 
      imagesavealpha($target, TRUE); 
       $empty = imagecolorallocatealpha($thumb,0x00,0x00,0x00,127); 
       imagefill($target, 0, 0, $empty); 
      imagecopyresized($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY); 
     } 

     // SHARPEN THE PIC 
     $sharpenMatrix = array 
     (array(-1.2, -1, -1.2) 
     , array(-1, 20, -1) 
     , array(-1.2, -1, -1.2) 
     ) 
     ; 
     $divisor = array_sum(array_map('array_sum', $sharpenMatrix)); 
     $offset = 0; 
     imageconvolution($target, $sharpenMatrix, $divisor, $offset); 

     if(imagepng($target, $image,9)){ 
      imagedestroy($target); 
     } 
     return $image; 
    } 
} 

그리고 예를 들어 호출이 것 나는이로 전환 be : upload("path/to/image/on/server.png", 400, 200, 2) 이미지 경로는 jpg 또는 png MIME 유형일 수 있습니다. 그러나 확장자는 반드시 .png 여야합니다. 확장 기능을 사용할 수있는 곳을 더 똑똑하게 만들 수 있다고 생각하지만,이 함수를 사용하는 현재 코드에서는 그대로 두는 것이 더 의미가 있습니다. 나는 결국 옵션을 추가하여 투명도를 켜거나 끄고 필요할 경우 검정과 같은 단색을 사용하고자합니다. 자유롭게 사용하고 수정하십시오.

나는이 here

관련 문제