在PHP中将JPEG/PNG转换为PNG用于数据库存储,但在显示时不能保持背景透明度/颜色


Converting JPEG/PNGs to PNG for database storage but can't keep background transparency/colour when displaying, in PHP

我有一个脚本,我用来转换jpeg或png png数据库存储,我编码文件为base64并将其存储在数据库中,我从数据库或缓存中拉文件,当在网站上显示它时,我只是从数据库或缓存中拉图像数据,并对其进行base64解码,并使用标准IMG标签显示它。

我遇到的问题是,无论背景是透明的还是我创建的图像的背景颜色,它总是显示为黑色时,显示在网页上。

我已经尝试了右边的许多问题,但似乎没有一个答案适合我。

<<p> 编码函数/strong>
public function encode($image, $resize = false, $dirLevel = '')
{
    $vTempFileName = TEMP_DIR . '_'.rand(1111111, 9999999) . '.png';
    // Convert image to PNG
    $image = imagecreatefromstring(file_get_contents($image));
    imagealphablending($image, true);
    imagepng($image, $vTempFileName);
    $vImageDetails = array(base64_encode(file_get_contents($vTempFileName)), filesize($vTempFileName));
    // Remove temporary file after processing
    @unlink($vTempFileName);
    return $vImageDetails;
}
<<p> 解码函数/strong>
echo base64_decode($image);

我也试过使用下面两个函数

要保存透明度,您需要添加imagesavealpha参见http://php.net/manual/en/function.imagesavealpha.php

public function encode($image, $resize = false, $dirLevel = '')
{
    $vTempFileName = TEMP_DIR . '_'.rand(1111111, 9999999) . '.png';
    // Convert image to PNG
    $image = imagecreatefromstring(file_get_contents($image));
    imagealphablending($image, true);
    imagesavealpha($image, true);
    imagepng($image, $vTempFileName);
    $vImageDetails = array(base64_encode(file_get_contents($vTempFileName)), filesize($vTempFileName));
    // Remove temporary file after processing
    @unlink($vTempFileName);
    return $vImageDetails;
}

imagefill将使用$transparent定义的所需颜色对所选坐标执行洪水填充。参见:http://php.net/manual/en/function.imagefill.php

$fillColor = imagecolorallocatealpha($image, 0, 0, 0, 127); 
imagefill($image, 0, 0, $fillColor); 

用所需的fillColor填充图像左上角相邻的颜色。

否则使用imagecolortransparent添加透明度参见http://php.net/manual/en/function.imagecolortransparent.php

$replaceBlack = imagecolorallocate($image, 0, 0, 0); 
imagecolortransparent($image, $replaceBlack);

这可能对你没有帮助,但是…如果可以避免,您确实不希望将图像存储到数据库中。你这么做有什么好的理由吗?文件系统擅长存储二进制文件。数据库擅长存储数据。为作业使用适当的工具—将其存储为文件。