2017-04-17 2 views
1

사용자 업로드 이미지를 수용하고 최대 너비/높이가 4,000px가되도록 비율을 조정하고 400px 및 800px 크기의 미리보기 이미지를 생성하는 기능이 있습니다. 투명 PNG를 처리하고 흰색 배경을 적용 할 수 있어야합니다.PHP GD 크기 조정으로 인해 아티팩트가 발생합니다

현재 코드에서는이 모든 작업을 수행하지만 JPEG의 일반적인 아티팩트를 추가합니다. 그것들은 세로 줄무늬이며 가까이서 보았을 때 바코드가 매우 흐려진 것처럼 보입니다 (400 % 확대 스크린 샷 첨부). 이는 크기가 조정되는 크기로 업로드 될 때 원래 이미지에서 발생합니다. 투명한 PNG는 훨씬 더 보편적 인 것처럼 보이지만 JPEG의 흰색 영역에서도 마찬가지입니다. JPEG 파일은 내가 문제가 환경에 특정 (안 Windows에서 PHP 7.0.1에서 우분투에서 PHP 7.1.3에서 발생하지만) 결론 80

400% Zoom of Originally All-White Area

function resize_image($file, $w, $h, $strict = false, $crop = false, $path = null, $thumbnail = false) 
{ 
    // Check for Valid Image + Calculate Ratio 
    list($width, $height) = getimagesize($file); 

    if (empty($width) || empty($height)) 
    { 
     echo json_encode(['result' => 'error', 'error' => 'file_format_invalid']); 
     http_response_code(405); 
     exit; 
    } 

    $r = $width/$height; 

    if (!$strict) 
    { 
     $w = min($w, $width); 
     $h = min($h, $height); 
    } 

    $wTa = min($w, 400); 
    $hTa = min($h, 400); 

    $wTb = min($w, 800); 
    $hTb = min($h, 800); 

    // Apply Crop Constraint 
    if ($crop) 
    { 
     if ($width > $height) 
     { 
      $width = ceil($width - ($width * abs($r - $w/$h))); 
      $widthTa = ceil($width - ($width * abs($r - $wTa/$hTa))); 
      $widthTb = ceil($width - ($width * abs($r - $wTb/$hTb))); 
     } 

     else 
     { 
      $height = ceil($height - ($height * abs($r - $w/$h))); 
      $heightTa = ceil($height - ($height * abs($r - $wTa/$hTa))); 
      $heightTb = ceil($height - ($height * abs($r - $wTa/$hTb))); 
     } 

     $newWidth = $w; 
     $newHeight = $h; 
    } 

    else 
    { 
     if ($w/$h > $r || $r < 1) 
     { 
      $newWidth = $h * $r; 
      $newWidthTa = $hTa * $r; 
      $newWidthTb = $hTb * $r; 

      $newHeight = $h; 
      $newHeightTa = $hTa; 
      $newHeightTb = $hTb; 
     } 

     else 
     { 
      $newHeight = $w/$r; 
      $newHeightTa = $wTa/$r; 
      $newHeightTb = $wTb/$r; 

      $newWidth = $w; 
      $newWidthTa = $wTa; 
      $newWidthTb = $wTb; 
     } 
    } 

    // Create, Resample + Return Image 
    $src = imagecreatefromstring(file_get_contents($file)); 
    $dst = imagecreatetruecolor($newWidth, $newHeight); 
    $fff = imagecolorallocate($dst, 255, 255, 255); 

    imagefill($dst, 0, 0, $fff); 
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); 

    if (!is_null($path)) 
    { 
     imagejpeg($dst, $path, 80); 

     if ($thumbnail) 
     { 
      $dstThumbA = imagecreatetruecolor($newWidthTa, $newHeightTa); 
      $dstThumbB = imagecreatetruecolor($newWidthTb, $newHeightTb); 

      $fffThumbA = imagecolorallocate($dstThumbA, 255, 255, 255); 
      $fffThumbB = imagecolorallocate($dstThumbB, 255, 255, 255); 

      imagefill($dstThumbA, 0, 0, $fffThumbA); 
      imagefill($dstThumbB, 0, 0, $fffThumbB); 

      imagecopyresampled($dstThumbA, $src, 0, 0, 0, 0, $newWidthTa, $newHeightTa, $width, $height); 
      imagecopyresampled($dstThumbB, $src, 0, 0, 0, 0, $newWidthTb, $newHeightTb, $width, $height); 

      imagejpeg($dstThumbA, str_replace('.jpg', '-thumb.jpg', $path), 80); 
      imagejpeg($dstThumbB, str_replace('.jpg', '[email protected]', $path), 80); 
     } 
    } 

    return $dst; 
} 
+1

'imagecopyresampled' 대신'imagecopyresized'를 사용하고 싶습니다. 아마도 도움이 될 것입니다. http://stackoverflow.com/questions/23200823/gd-quality-issue-with-transparent -pngs || http://stackoverflow.com/questions/23993901/imagecopyresampled-introduces-artifacts-in-transparent-png –

+0

흠, 좋은 생각, 'imagecopyresized'는 효과가 있으며, 인공물이 없어도 수용할만한 별명이 너무 많았습니다. 나는이 증상이 우분투에서 PHP 7.1.3에서 발생하지만 개발중인 Windows에서는 PHP 7.0.1에서 발생하지 않는다는 것을 알아 차렸다. 어쩌면 설정 관련? –

답변

0

품질에 저장되는 . php7.1php7.1-gd을 재설치해도 아무런 효과가 없습니다.

는 궁극적으로 나는 코드의 훨씬 더 간결 블록의 결과로, 총알을 물고 ImageMagick과 함께 다시하기로 결정 setImageCompression()

$magickSource = new Imagick(); 
$magickSource->readImageBlob(file_get_contents($file)); 
$magickSource = $magickSource->flattenImages(); 

$magickFull = clone $magickSource; 
$magickFull->resizeImage(min($originalWidth, $newWidth), min($originalHeight, $newHeight), Imagick::FILTER_LANCZOS, 1, true); 
$magickFull->setImageCompression(Imagick::COMPRESSION_JPEG); 
$magickFull->setImageCompressionQuality(75); 
$magickFull->stripImage(); 
$magickFull->writeImage($path); 
$magickFull->destroy(); 

if ($thumbnail) 
{ 
    $magickThumb = clone $magickSource; 
    $magickThumb->resizeImage(min($originalWidth, 400), min($originalHeight, 400), Imagick::FILTER_LANCZOS, 1, true); 
    $magickThumb->setImageCompression(Imagick::COMPRESSION_JPEG); 
    $magickThumb->setImageCompressionQuality(75); 
    $magickThumb->stripImage(); 
    $magickThumb->writeImage(str_replace('.jpg', '-thumb.jpg', $path)); 
    $magickThumb->destroy(); 
} 

통화, setImageCompressionQualitystripImage() 결합 filesizes의 53 % 감소를 산출 . (Source)

관련 문제