Загрузить png изображение черный фон

Когда я загружаю изображение png с помощью php, цвет фона изображения устанавливается на черный.
Я пытался установить прозрачный фон, но это не работает.
Это мой код:

if( $image_type == IMAGETYPE_PNG )
{
    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
    imagealphablending($dst_r, false);
    imagesavealpha($dst_r, true);
    imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
    imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w, $targ_h, $targ_w, $targ_h);
    imagepng($dst_r,$filename, 9);
}

Отредактировано:

Я думал, что закончил с этой проблемой, но я был неправ:

$targ_w_thumb = $targ_h_thumb = 220;
if($image_type == IMAGETYPE_PNG)
{
    $dst_r = ImageCreateTrueColor($targ_w_thumb, $targ_h_thumb);
    imagealphablending($dst_r, false);
    imagesavealpha($dst_r, true);
    imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
    imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w_thumb, $targ_h_thumb, $targ_w, $targ_h);
    imagepng($dst_r,$filename, 9);
}

person motis10    schedule 23.07.2015    source источник


Ответы (2)


imagecreatetruecolor() создает изображение, заполненное непрозрачным черным цветом. Если вы сначала не заполните свое новое изображение прозрачностью, черный цвет проявится позже.

Все, что вам нужно, это imagefill() прозрачного цвета, а именно черного, вот так:

imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));  // transparency values range from 0 to 127

Применительно к вашему коду это должно работать:

if( $image_type == IMAGETYPE_PNG )
{
    $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
    imagealphablending($dst_r, false);
    imagesavealpha($dst_r, true);

    // Paint the watermark image with a transparent color to remove the default opaque black.
    // If we don't do this the black shows through later colours.
    imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));

    imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w, $targ_h, $targ_w, $targ_h);
    imagepng($dst_r,$filename, 9);
}
person Community    schedule 23.07.2015
comment
Все еще не работает с вашим предложением imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127)); - person motis10; 24.07.2015

Я не знаю почему, но когда я добавил targ_w_thumb, он заработал нормально + imagefill():

    $targ_w_thumb = $targ_w_thumb = 200;
    $dst_r = ImageCreateTrueColor($targ_w_thumb, $targ_h_thumb);
    imagealphablending($dst_r, false);
    imagesavealpha($dst_r, true);
    imagefill($dst_r,0,0,imagecolorallocatealpha($dst_r, 0,0,0,127));
    imagecopyresampled($dst_r, $this->image, 0, 0, $targ_x, $targ_y, $targ_w_thumb, $targ_h_thumb, $targ_w, $targ_h);
    imagepng($dst_r,$filename, 9);
person motis10    schedule 24.07.2015