简体   繁体   English

上载png图片黑色背景

[英]Upload png image black background

When i upload a png image with php, the background color of the image is setted to black. 当我使用php上传png图像时,图像的背景色设置为黑色。
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. imagecreatetruecolor()创建一个不透明黑色填充的图像。 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() ,即黑色,就像这样:

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时,它的工作正常+ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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