source

PHP의 GDlib imagecopyresampled 사용 시 PNG 이미지 투명도를 유지할 수 있습니까?

itover 2022. 12. 21. 22:31
반응형

PHP의 GDlib imagecopyresampled 사용 시 PNG 이미지 투명도를 유지할 수 있습니까?

다음 PHP 코드 스니펫은 GD를 사용하여 브라우저에 업로드된 PNG 크기를 128x128로 조정합니다.원래 이미지의 투명 영역이 단색으로 교체되고 있다는 점만 제외하면 매우 효과적입니다. 내 경우 검은색입니다.

그럼에도 불구하고.imagesavealpha준비가 되어 있고 뭔가 잘못됐어

재샘플링된 이미지의 투명성을 유지하는 가장 좋은 방법은 무엇일까요?

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile );    
imagesavealpha( $targetImage, true );

$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );

날 위해서 그랬어씨제이오즈 고마워요

대상 이미지에는 소스 이미지가 아닌 알파 설정이 필요합니다.

편집: 전체 교체 코드입니다.아래의 답변과 그 코멘트를 참조해 주세요.이것은 어떤 식으로든 완벽하다고 보장되는 것은 아니지만, 그 당시에는 제 욕구를 충족시켰습니다.

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile ); 

$targetImage = imagecreatetruecolor( 128, 128 );   
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );

imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );

왜 그렇게 일을 복잡하게 만드세요?다음은 내가 사용하는 것이고 지금까지 그것은 나를 위해 일을 해 주었다.

$im = ImageCreateFromPNG($source);
$new_im = imagecreatetruecolor($new_size[0],$new_size[1]);
imagecolortransparent($new_im, imagecolorallocate($new_im, 0, 0, 0));
imagecopyresampled($new_im,$im,0,0,0,0,$new_size[0],$new_size[1],$size[0],$size[1]);

이 방법이 효과가 있을 거라고 생각합니다.

$srcImage = imagecreatefrompng($uploadTempFile);
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);

edit: PHP 문서 중 누군가가 클레임합니다.imagealphablending거짓이 아니라 진실이어야 합니다.YMMV

일부 사용자에게 도움이 될 수 있는 추가 정보:

이미지를 빌드하는 동안 이미지 알파파블렌딩을 전환할 수 있습니다.저는 이것이 필요한 구체적인 경우 투명 배경에 반투명 PNG를 결합하고 싶었습니다.

먼저 이미지 알파파블링을 false로 설정하고 새로 생성된 실제 색상 이미지를 투명한 색으로 채웁니다.이미지 알파핑이 참인 경우 투명 채우기가 검은색 기본 배경과 병합되어 검은색으로 나타나므로 아무 일도 일어나지 않습니다.

그런 다음 이미지 알파파일을 참으로 전환하고 일부 PNG 이미지를 캔버스에 추가하여 배경 일부를 볼 수 있습니다(예:전체 이미지가 채워지지 않습니다).

그 결과 투명한 배경과 여러 개의 결합된 PNG 이미지를 가진 이미지가 생성됩니다.

JPEG/GIF/PNG와 같은 이미지 크기 조정 기능을 만들었습니다.copyimageresamplePNG 이미지는 여전히 투명성을 유지합니다.

$myfile=$_FILES["youimage"];

function ismyimage($myfile) {
    if((($myfile["type"] == "image/gif") || ($myfile["type"] == "image/jpg") || ($myfile["type"] == "image/jpeg") || ($myfile["type"] == "image/png")) && ($myfile["size"] <= 2097152 /*2mb*/) ) return true; 
    else return false;
}

function upload_file($myfile) {         
    if(ismyimage($myfile)) {
        $information=getimagesize($myfile["tmp_name"]);
        $mywidth=$information[0];
        $myheight=$information[1];

        $newwidth=$mywidth;
        $newheight=$myheight;
        while(($newwidth > 600) || ($newheight > 400 )) {
            $newwidth = $newwidth-ceil($newwidth/100);
            $newheight = $newheight-ceil($newheight/100);
        } 

        $files=$myfile["name"];

        if($myfile["type"] == "image/gif") {
            $tmp=imagecreatetruecolor($newwidth,$newheight);
            $src=imagecreatefromgif($myfile["tmp_name"]);
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);
            $con=imagegif($tmp, $files);
            imagedestroy($tmp);
            imagedestroy($src);
            if($con){
                return true;
            } else {
                return false;
            }
        } else if(($myfile["type"] == "image/jpg") || ($myfile["type"] == "image/jpeg") ) {
            $tmp=imagecreatetruecolor($newwidth,$newheight);
            $src=imagecreatefromjpeg($myfile["tmp_name"]); 
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);
            $con=imagejpeg($tmp, $files);
            imagedestroy($tmp);
            imagedestroy($src);
            if($con) {  
                return true;
            } else {
                return false;
            }
        } else if($myfile["type"] == "image/png") {
            $tmp=imagecreatetruecolor($newwidth,$newheight);
            $src=imagecreatefrompng($myfile["tmp_name"]);
            imagealphablending($tmp, false);
            imagesavealpha($tmp,true);
            $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
            imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent); 
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);
            $con=imagepng($tmp, $files);
            imagedestroy($tmp);
            imagedestroy($src);
            if($con) {
                return true;
            } else {
                return false;
            }
        }   
    } else
          return false;
}

이 방법이 효과가 있을 것 같습니다.

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile );

$targetImage = imagecreatetruecolor( 128, 128 );

$transparent = imagecolorallocate($targetImage,0,255,0);
imagecolortransparent($targetImage,$transparent);
imagefilledrectangle($targetImage,0,0,127,127,$transparent);

imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );

단점은 이미지가 100% 녹색 픽셀마다 제거된다는 것입니다.어쨌든 도움이 되었으면 합니다. :)

투명성 유지를 재레이딩한 후 다른 투고에서 설명한 것처럼 yes를 true로 설정해야 합니다.알파 플래그 이미지 알파파블렌딩()을 사용하려면 false로 설정해야 합니다.그렇지 않으면 동작하지 않습니다.

그리고 당신의 코드에서 두 가지 사소한 것을 발견했습니다.

  1. getimagesize()imagecopyresmapled()
  2. $uploadWidth ★★★★★★★★★★★★★★★★★」$uploadHeightshould be -1은 코드레이트가 '''에서 입니다.0 and1그래서 빈 픽셀에 복사합니다. ★★★★★★★★★★★★★★★★:imagesx($targetImage) - 1 ★★★★★★★★★★★★★★★★★」imagesy($targetImage) - 1 :) , , , , , , , , , , , )

이게 제 전체 테스트 코드입니다.난 괜찮아

$imageFileType = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
$filename = 'test.' . $imageFileType;
move_uploaded_file($_FILES["image"]["tmp_name"], $filename);

$source_image = imagecreatefromjpeg($filename);

$source_imagex = imagesx($source_image);
$source_imagey = imagesy($source_image);

$dest_imagex = 400;
$dest_imagey = 600;
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);

imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

imagesavealpha($dest_image, true);
$trans_colour = imagecolorallocatealpha($dest_image, 0, 0, 0, 127);
imagefill($dest_image, 0, 0, $trans_colour);

imagepng($dest_image,"test1.png",1);

이미지의 「」에 .width ★★★★★★★★★★★★★★★★★」height되는 값imagecopyresampled★★★ .실제 소스 이미지 크기보다 클 경우 나머지 이미지 영역은 검은색으로 채워집니다.

저는 Ceejayoz와 Cheekysoft의 답변을 조합하여 최고의 결과를 얻었습니다.image alphapableending() 및 imagesavealpha()가 없으면 이미지가 선명하지 않습니다.

$img3 = imagecreatetruecolor(128, 128);
imagecolortransparent($img3, imagecolorallocate($img3, 0, 0, 0));
imagealphablending( $img3, false );
imagesavealpha( $img3, true );
imagecopyresampled($img3, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight);
imagepng($img3, 'filename.png', 9);

★★★★★★★★★★★★★★★★에 문제가 있는 에게는,imagecopyresampled ★★★★★★★★★★★★★★★★★」imagerotate검은 막대를 배경으로 코드 예를 찾았습니다.

https://qna.habr.com/q/646622#answer_1417035

        // get image sizes (X,Y)
        $wx = imagesx($imageW);
        $wy = imagesy($imageW);

        // create a new image from the sizes on transparent canvas
        $new = imagecreatetruecolor($wx, $wy);

        $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);
        $rotate = imagerotate($imageW, 280, $transparent);
        imagealphablending($rotate, true);
        imagesavealpha($rotate, true);

        // get the newest image X and Y
        $ix = imagesx($rotate);
        $iy = imagesy($rotate);

        //copy the image to the canvas
        imagecopyresampled($destImg, $rotate, 940, 2050, 0, 0, $ix, $iy, $ix, $iy);

언급URL : https://stackoverflow.com/questions/32243/can-png-image-transparency-be-preserved-when-using-phps-gdlib-imagecopyresample

반응형