Проблема обновления кернинга PHP с функциями imagettftext() и imagefttext()

Наш сервер разработки недавно был обновлен до версии PHP 5.2.13. С этим обновлением мы обнаружили, что наши png-изображения имеют проблемы с кернингом (расстоянием между буквами). Мы перепробовали множество шрифтов и пока не нашли решения.

Мы создаем изображения с помощью библиотеки GD и записываем текст в изображения с помощью файлов шрифтов и функций imagettftext() или imagefttext().

Кто-нибудь еще столкнулся с этим? Я что-то неправильно понимаю или это должно быть представлено в PHP как ошибка? Есть ли какие-нибудь интересные обходные пути, о которых я еще не подумал?

Вот пример нового и старого полужирного шрифта Tahoma. С другими шрифтами (жирным и нежирным) та же проблема. Некоторые буквы и цифры кажутся смещенными от центра или что-то в этом роде.

Плохо - новый PHP

Старый добрый PHP v5.2.11 (слова немного отличаются, потому что это наш сервер разработки, а другой — рабочий сервер)


person Neil Neyman    schedule 09.04.2010    source источник
comment
Каков результат foreach(array('GD_VERSION', 'GD_EXTRA_VERSION','GD_BUNDLED') as $c) echo $c, ': ', constant($c), "\n"; в обеих версиях php?   -  person VolkerK    schedule 09.04.2010
comment
GD_VERSION: 2.0.35 GD_EXTRA_VERSION: GD_BUNDLED: 1 То же самое на обоих серверах.   -  person Neil Neyman    schedule 10.04.2010


Ответы (2)


«Отслеживание» — это аналогичный термин для того, насколько плотный или свободный текст установлен. Возможно, вам повезет погуглить, например, этот результат.

person cowbellemoo    schedule 09.04.2010
comment
Это интересно. Спасибо, я проверю. У нас много кода, и мы надеемся, что нам не придется заменять сотни вызовов функций, но на данный момент лучшего выбора может и не быть. :-/ Конечно, я добавлю это в качестве условия поиска в понедельник, когда вернусь. - person Neil Neyman; 10.04.2010

Кернинг у нас не работал из-за используемого нами шрифта, поэтому нам пришлось использовать ручной кернинг для определенных комбинаций букв, таких как AV, AW и т. д.

/**
 * This function lets you write a string with your own letter spacing ($t)
 * and kern specific letter combinations like AV
 * 
 * @param type $im An image resource, returned by one of the image creation functions
 * @param type $size The font size. Depending on your version of GD, this should be specified as the pixel size (GD1) or point size (GD2).
 * @param type $angle The angle in degrees, with 0 degrees being left-to-right reading text. Higher values represent a counter-clockwise rotation. For example, a value of 90 would result in bottom-to-top reading text.
 * @param type $t Letter Spacing
 * @param type $k Kerning Spacing
 * @param type $x The coordinates given by x and y will define the basepoint of the first character (roughly the lower-left corner of the character). This is different from the imagestring(), where x and y define the upper-left corner of the first character. For example, "top left" is 0, 0.
 * @param type $y The y-ordinate. This sets the position of the fonts baseline, not the very bottom of the character.
 * @param type $color The color index. Using the negative of a color index has the effect of turning off antialiasing. See imagecolorallocate().
 * @param type $font The path to the TrueType font you wish to use.
 * @param type $text Text to write/print to the image
 */
function ImageTTFTextWithSpacing($im, $size, $angle, $t, $k, $x, $y, $color, $font, $text) {
    $numchar = strlen($text);
    for($i = 0; $i < $numchar; $i++) {
        # Assign character
        $char[$i] = substr($text, $i, 1);

        //Top is wider than bottom of character
        $up = ['Y','V','W'];
        //Bottom is wider than top of character
        $down = ['A'];
        //From the second letter on
        if( $i > 0 && 
                //check whether we have TOP and BOTTOM type character 
                //next to each other so we need to adjust spacing
                ((in_array($char[$i], $up) && in_array($char[$i-1], $down)) || 
                (in_array($char[$i-1], $up) && in_array($char[$i], $down)) )) {
            $w -= $k;
        }

        # Write character
        imagettftext($im, $size, $angle, ($x + $w + ($i * $t)), $y, $color, $font, $char[$i]);

        # Get width of character
        $width = imagettfbbox($size, $angle, $font, $char[$i]);
        $w = $w + $width[2];
    }
}
person ShQ    schedule 31.08.2016