简体   繁体   English

在使用gd在php中调整图像大小后的黑色背景

[英]Black background after resizing image in php using gd

I use the below code to resize images (jpg, png, gif). 我使用下面的代码来调整图像大小(jpg,png,gif)。 The code is working perfectly. 代码工作得很好。 But the problem is after resizing the images, all transparent images (both png and gif) have a black background. 但问题是在调整图像大小后,所有透明图像(png和gif)都有黑色背景。

How can I maintain the transparency so that resized images will have not have black background? 如何保持透明度,使调整后的图像不具有黑色背景?

 $target = 'uploads/'.$newname;

 move_uploaded_file( $_FILES['file']['tmp_name'], $target);;

 $filename=$newname;
 if($ext=='jpg'||$ext=='jpeg') {
        $im = imagecreatefromjpeg('uploads/'.$filename);
    } else if ($ext=='gif') {
        $im = imagecreatefromgif('uploads/'.$filename);
    } else if ($ext=='png') {
        $im = imagecreatefrompng('uploads/'.$filename);
    }
    $ox = imagesx($im);
    $oy = imagesy($im);
    $nm = imagecreatetruecolor(400, 300);
    imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);
     imagejpeg($nm,  'thumbnails/' . $filename);

imagesavealpha() sets the flag to attempt to save full alpha channel information (as opposed to single-color transparency) when saving PNG images. imagesavealpha()设置标志以在保存PNG图像时尝试保存完整的Alpha通道信息(而不是单色透明度)。

You have to unset alphablending (imagealphablending($im, false)), to use it. 你必须取消设置alphablending(imagealphablending($ im,false))才能使用它。

Try adding 尝试添加

imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );

Here: 这里:

.
.
$nm = imagecreatetruecolor(400, 300);
imagealphablending( $nm, FALSE );
imagesavealpha( $nm, TRUE );
.
.

Also consider using imagecopyresampled instead of imagecopyresized . 还可以考虑使用imagecopyresampled而不是imagecopyresized

imagecopyresampled() smoothly interpolates pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. imagecopyresampled()平滑地插入像素值,以便特别是减小图像的大小仍然保持很大的清晰度。

Use imagecopyresampled($nm, $im, 0,0,0,0,400,300,$ox,$oy); 使用imagecopyresampled($nm, $im, 0,0,0,0,400,300,$ox,$oy);

Instead of imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy); 而不是imagecopyresized($nm, $im, 0,0,0,0,400,300,$ox,$oy);

I also had similar troubles where a black background still appeared when using: 我也有类似的麻烦,使用时仍然出现黑色背景:

imagealphablending($image, false);
imagesavealpha($image, true);

I found the below combination to be successful though: 我发现下面的组合是成功的:

imagecolortransparent($image, imagecolorallocate($thumbnail, 0, 0, 0));
imagealphablending($image, false);

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

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