简体   繁体   中英

Upload png image black background

When i upload a png image with php, the background color of the image is setted to black.
I tried to set it to transparent background but it doesn't work.
This is my code :

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);
}

Edited:

I tought i'v finished with this problem but i was wrong:

$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);
}

imagecreatetruecolor() creates an image filled with opaque black. Unless you fill your new image with transparency first, the black will show through later.

All you need is an imagefill() with a transparent colour - namely black, like this:

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

Applied to your code, this should work:

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);
}

I dont know why but when i added targ_w_thumb its work fine + 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM