【问题标题】:GD! Converting a png image to jpeg and making the alpha by default white and not blackGD!将 png 图像转换为 jpeg 并使 alpha 默认为白色而不是黑色
【发布时间】:2011-02-03 22:14:15
【问题描述】:

我尝试了类似的方法,但它只是使图像的背景变白,而不一定是图像的 alpha。我只想将所有内容都上传为 jpg,所以如果我能以某种方式“展平”一个 png 图像,其中一些透明地默认为白色,这样我就可以将它用作 jpg。感谢任何帮助。谢谢。

$old = imagecreatefrompng($upload);
$background = imagecolorallocate($old,255,255,255);
imagefill($old, 0, 0, $background);
imagealphablending($old, false);
imagesavealpha($old, true);

【问题讨论】:

    标签: php image-processing image-manipulation gd


    【解决方案1】:
    <?php
    $input_file = "test.png";
    $output_file = "test.jpg";
    
    $input = imagecreatefrompng($input_file);
    $width = imagesx($input);
    $height = imagesy($input);
    $output = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($output,  255, 255, 255);
    imagefilledrectangle($output, 0, 0, $width, $height, $white);
    imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
    imagejpeg($output, $output_file);
    

    【讨论】:

    • 我在这个问题上搞砸了很长时间,这个答案是完美的,现在我已经看到了。非常感谢。
    • 不确定这对性能有多大影响,但我建议在imagecreatefrompng() 之后使用imagesx($input) 和imagesy($input) 而不是getimagesize(),以避免再次从文件中读取和解析标题。
    猜你喜欢
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2018-10-27
    • 2021-04-28
    相关资源
    最近更新 更多