PHP Conference Japan 2024

imagepalettetotruecolor

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagepalettetotruecolor将基于调色板的图像转换为真彩色图像

说明

imagepalettetotruecolor(GdImage $image): bool

将由类似 imagecreate() 函数创建的基于调色板的图像转换为类似 imagecreatetruecolor() 的真彩色图像。

参数

image

一个由图像创建函数(例如 imagecreatetruecolor())返回的 GdImage 对象。

返回值

如果转换完成或源图像已经是真彩色图像,则返回 true,否则返回 false

更新日志

版本 说明
8.0.0 image 现在需要一个 GdImage 实例;之前,需要有效的 gd resource

示例

示例 #1 将任何图像对象转换为真彩色

<?php
// 向后兼容
if(!function_exists('imagepalettetotruecolor'))
{
function
imagepalettetotruecolor(&$src)
{
if(
imageistruecolor($src))
{
return(
true);
}

$dst = imagecreatetruecolor(imagesx($src), imagesy($src));

imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
imagedestroy($src);

$src = $dst;

return(
true);
}
}

// 辅助闭包
$typeof = function() use($im)
{
echo
'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL;
};

// 创建一个基于调色板的图像
$im = imagecreate(100, 100);
$typeof();

// 将其转换为真彩色
imagepalettetotruecolor($im);
$typeof();

// 释放内存
imagedestroy($im);
?>

以上示例的输出

typeof($im) = palette
typeof($im) = true color

参见

添加注释

用户贡献的注释 3 条

up
1
Polda18
10 年前
PHP 版本 5.4.24 不支持此函数(它尚未定义)。要解决此问题,您必须将图像资源复制到由函数 imagecreatetruecolor() 创建的新图像中;

从 GIF 文件加载图像的示例

$image = imagecreatefromgif("path/to/gif/file.gif"); // 从 GIF 创建图像
$width = imagesx($image); // 获取源图像的宽度
$height = imagesy($image); // 获取源图像的高度
$image2 = imagecreatetruecolor($width,$height); // 创建具有给定宽度和高度的真彩色新图像
imagecopy($image2,$image,0,0,0,0,$width,$height); // 将源图像复制到新图像

header("Content-Type: image/jpeg"); // 设置 JPG 图像的标头
imagejpg($image2); // 在浏览器中渲染 JPG 图像

imagedestroy($image); // 释放内存
imagedestroy($image2);
up
0
walf - iftfy
7 年前
这是 walf 解决方案的有效版本

<?php
// 向后兼容
if (!function_exists('imagepalettetotruecolor')) {
function
imagepalettetotruecolor(&$src) {
if (
imageistruecolor($src)) {
return
true;
}

$dst = imagecreatetruecolor(imagesx($src), imagesy($src));

imagealphablending($dst, false);// 防止与默认黑色混合
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);// 如果需要,更改RGB值,但保持alpha值为127
imagefilledrectangle($dst, 0, 0, imagesx($src), imagesy($src), $transparent);// 比填充更简单
imagealphablending($dst, true);// 恢复默认混合

imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
imagedestroy($src);

$src = $dst;
return
true;
}
}
?>
up
-2
walf
10 年前
向后兼容性示例不能保留透明度。您必须首先清除新图像上的默认黑色背景。

<?php
// 向后兼容
if (!function_exists('imagepalettetotruecolor')) {
function
imagepalettetotruecolor(&$src) {
if (
imageistruecolor($src)) {
return
true;
}

$dst = imagecreatetruecolor(imagesx($src), imagesy($src));

imagealphablending($dst, false);// 防止与默认黑色混合
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);// 如果需要,更改RGB值,但保持alpha值为127
imagefilledrectangle($dst, 0, 0, $imagesx($src), imagesy($src), $transparent);// 比填充更简单
imagealphablending($dst, true);// 恢复默认混合

imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
imagedestroy($src);

$src = $dst;
return
true;
}
}
?>
To Top