PHP imagecopy с прозрачным фоном - PullRequest
       33

PHP imagecopy с прозрачным фоном

7 голосов
/ 11 октября 2011

Я использую этот код для создания изображения из другого изображения PNG, фон по умолчанию черный.У меня вопрос, как установить прозрачный фон?

$input = imagecreatefrompng('image.png');
$output = imagecreatetruecolor(50, 50);

imagecopy($output, $input, 4,0, 8,8, 8,8);
imagecopy... etc.

header('Content-Type: image/png');
imagepng($output);

Есть ли простой способ сделать это?Спасибо

Ответы [ 6 ]

11 голосов
/ 11 октября 2011

Устанавливает прозрачный цвет в данном изображении .

int imagecolortransparent ( resource $image [, int $color ] )

Вот ссылка

8 голосов
/ 11 октября 2011

Поскольку функция PHP imagecopymerge не работает с альфа-каналом, вам нужно использовать функцию из первого комментария на этой странице imagecopymerge_alpha: http://php.net/manual/en/function.imagecopymerge.php

Просто используйте прозрачное изображение в качестве основы и объедините его с нужным изображением.

Я опробовал его, и он отлично работает для моего проекта.

1 голос
/ 02 ноября 2013
imagealphablending($input, true);
imagesavealpha($input, true);

imagealphablending($output, true);
imagesavealpha($output, true);
0 голосов
/ 30 октября 2018

Полный кредит идет на: http://consistentcoder.com/combine-a-transparent-png-image-on-top-of-another-image-with-php

Следующий код наложит изображение переднего плана на фоновое изображение, в то время как сохранит прозрачность наложения :

//set the source image (foreground)
$sourceImage = 'table.png';

//set the destination image (background)
$destImage = 'create-a-surreal-head-of-tree-photo-manipulation.jpg';

//get the size of the source image, needed for imagecopy()
list($srcWidth, $srcHeight) = getimagesize($sourceImage);

//create a new image from the source image
$src = imagecreatefrompng($sourceImage);

//create a new image from the destination image
$dest = imagecreatefromjpeg($destImage);

//set the x and y positions of the source image on top of the destination image
$src_xPosition = 75; //75 pixels from the left
$src_yPosition = 50; //50 pixels from the top

//set the x and y positions of the source image to be copied to the destination image
$src_cropXposition = 0; //do not crop at the side
$src_cropYposition = 0; //do not crop on the top

//merge the source and destination images
imagecopy($dest,$src,$src_xPosition,$src_yPosition,
          $src_cropXposition,$src_cropYposition,
          $srcWidth,$srcHeight);

//output the merged images to a file
/*
 * '100' is an optional parameter,
 * it represents the quality of the image to be created,
 * if not set, the default is about '75'
 */
imagejpeg($dest,
    'combine-a-transparent-png-image-on-top-of-another-image-with-php-01.jpg',
    100);

//destroy the source image
imagedestroy($src);

//destroy the destination image
imagedestroy($dest);
0 голосов
/ 13 августа 2018

Ни одно из решений не работало для меня, оно всегда конвертировало бы прозрачные пиксели исходного изображения в черный на конечном изображении. То, что работало, меняло imagecopy / imagecopymerge / imagecopymerge_alpha на imagecopy с повторной выборкой и просто передавая одинаковую ширину и высоту дважды.

    //Create destination image.
    $png = imagecreatetruecolor(1024, 1024);
    imagealphablending($png, false);
    imagesavealpha($png, true);
    //Make destination image be all transparent.
    $color = imagecolorallocatealpha($png, 0, 0, 0, 127); //127 means completely transparent.
    imagefill($png, 0, 0, $color);

    //Load source image.
    $png2 = imagecreatefrompng($sourceurl);
    imagealphablending($png2, false);
    imagesavealpha($png2, true);
    $sizex = imagesx($png2);
    $sizey = imagesy($png2);

    //Copy to destination and save to file.
    imagecopyresampled( $png, $png2, 
    0, 0,
    0, 0, 
    $sizex, $sizey, 
    $sizex, $sizey);
    imagepng($png, "result.png");
0 голосов
/ 11 октября 2011

Или возможно

int imagesavealpha($img,true);

http://www.php.net/manual/en/function.imagesavealpha.php

...