Sometimes this function gives ugly/dull colors (especially when ncolors < 256). Here is a replacement that uses a temporary image and ImageColorMatch() to match the colors more accurately. It might be a hair slower, but the file size ends up the same:
<?php
function ImageTrueColorToPalette2( $image, $dither, $ncolors )
{
$width = imagesx( $image );
$height = imagesy( $image );
$colors_handle = ImageCreateTrueColor( $width, $height );
ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
ImageTrueColorToPalette( $image, $dither, $ncolors );
ImageColorMatch( $colors_handle, $image );
ImageDestroy( $colors_handle );
}
?>imagetruecolortopalette
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
imagetruecolortopalette
Референца за `function.imagetruecolortopalette.php` со подобрена типографија и навигација.
imagetruecolortopalette
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagetruecolortopalette — Претвори слика во вистинска боја во палета слика
= NULL
imagetruecolortopalette() конвертира слика во вистинска боја во палета слика. Кодот за оваа функција првично беше извлечен од кодот на библиотеката Independent JPEG Group, што е одлично. Кодот е изменет за да се зачува што е можно повеќе информации за алфа каналот во резултирачката палета, покрај зачувувањето на боите што е можно подобро. Ова не работи толку добро како што може да се очекува. Обично е најдобро едноставно да се произведе излезна слика во вистинска боја наместо тоа, што гарантира највисок квалитет на излезот.
Параметри
-
image А GdImage не применува никакво полнење, така што ширината на сликата мора да биде множител на 8. Ова ограничување веќе не важи од PHP 7.0.9. imagecreatetruecolor().
dither-
Индицира дали сликата треба да биде дитерирана - ако е
trueтогаш ќе се користи дитерирање што ќе резултира со пошарена слика, но со подобра апроксимација на боите. num_colors-
Поставува максимален број на бои што треба да се задржат во палетата.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
image беше вратено при неуспех. GdImage
инстанца сега; претходно, валидна gd resource се очекуваше.
|
Примери
Пример #1 Конвертирање на слика во вистинска боја во слика базирана на палета
<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);
// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);
// Save the image
imagepng($im, './paletteimage.png');
?>Белешки од корисници 6 белешки
>> zmorris at zsculpt dot com
I don't have the imageColorMatch() function on my server, but I could slighty improve the quality of the GIF/PNG image by converting it first to 256 colors, then to true colors and finally to the desired number of colors.
<?php
$dither = true;
$colors = 64;
$tmp = imageCreateFromJpeg('example.jpg');
$width = imagesX($tmp);
$height = imagesY($tmp);
imageTrueColorToPalette($tmp, $dither, 256);
$image = imageCreateTrueColor($width, $height);
imageCopy($image, $tmp, 0, 0, 0, 0, $width, $height);
imageDestroy($tmp);
imageTrueColorToPalette($image, $dither, $colors);
?>
Final $image will still have less than 64 colors, but more than if it was directly converted to 64 colors, and they match the JPEG image more.
Dunno why true colors to palette conversions are such a problem...The palette created by this function often looks quite awful (at least it did on all of my test images). A better way to convert your true-colour images is by first making a resized copy of them with imagecopyresampled() to a 16x16 pixel destination. The resized image then contains only 256 pixels, which is exactly the number of colours you need. These colours usually look a lot better than the ones generated by imagetruecolortopalette().
The only disadvantage to this method I have found is that different-coloured details in the original image are lost in the conversion.If you open a truecolor image (with imageCreateFromPng for example), and you save it directly to GIF format with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.TrueColor images should be converted to Palette images with this function. So, if you want to use imagecolorstotal() function [ http://php.net/manual/en/function.imagecolorstotal.php ] , you should first convert the image to a palette image with imagetruecolortopalette();a basic palette to true color function
<?php
function imagepalettetotruecolor(&$img)
{
if (!imageistruecolor($img))
{
$w = imagesx($img);
$h = imagesy($img);
$img1 = imagecreatetruecolor($w,$h);
imagecopy($img1,$img,0,0,0,0,$w,$h);
$img = $img1;
}
}
?>