PHP Velho Oeste 2024

imagepsbbox

(PHP 4, PHP 5)

imagepsbbox Выдает параметры рамки, обрамляющей текст написанный шрифтом PostScript Type1

Внимание

Эта функция УДАЛЕНА в PHP 7.0.0.

Описание

imagepsbbox ( string $text , resource $font , int $size ) : array
imagepsbbox ( string $text , resource $font , int $size , int $space , int $tightness , float $angle ) : array

Выдает параметры рамки, обрамляющей текст написанный шрифтом PostScript Type1.

Параметры рамки рассчитываются на основе метрики символов и в общем случае могут не совпадать с реальным размером текста после его прорисовки на изображении. Если угол составляет 0 градусов, текст может занимать на 1 пиксел больше в каждом направлении.

Список параметров

text

Текст, который должен быть записан.

font_index

Ресурс шрифта, возвращаемый функцией imagepsloadfont().

size

size задается в пикселах.

space

Позволяет изменять размер пробела в шрифте. Значение аргумента добавляется к значению по умолчанию для шрифта и может быть отрицательным. Значение задается в условных единицах, одна единица соответствует 1/1000 ширины буквы m этого шрифта.

tightness

tightness позволяет регулировать расстояние между символами. Значение аргумента добавляется к значению по умолчанию для шрифта и может быть отрицательным. Значение задается в условных единицах, одна единица соответствует 1/1000 ширины буквы m этого шрифта.

angle

angle задается в градусах.

Возвращаемые значения

Возвращает массив со следующими элементами:

0 левая x-координата
1 верхняя y-координата
2 правая x-координата
3 нижняя y-координата

Список изменений

Версия Описание
7.0.0Поддержка T1Lib удалена из PHP и эта функция, соответственно, тоже.

Примеры

Пример #1 Пример использования imagepsbbox()

<?php
// Создание изображения
$im imagecreatetruecolor(200200);

// Выделение цветов
$black imagecolorallocate($im000);
$white imagecolorallocate($im255255255);

// Загрузка шрифта PostScript
$font imagepsloadfont('font.pfm');

// Создание рамки
$bbox imagepsbbox('Простой пример текста'$font12); 

// Определим X и Y координаты
$x = ($bbox[2] / 2) - 10;
$y = ($bbox[3] / 2) - 10;

// Запишем текст на изображение
imagepstext($im'Простой пример текста'$font12$black$white$x$y);

// Вывод и освобождение памяти
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

Примечания

Замечание: Эта функция доступна только в случае, если PHP был скомпилирован с опцией --with-t1lib[=DIR].

Смотрите также

  • imagepstext() - Рисование текста поверх изображения, используя шрифты PostScript Type1

add a note add a note

User Contributed Notes 4 notes

up
0
eikie
15 years ago
I have a given image width and need to render a long string on that image. By using the following function I'm, able to get an array of strings which each will fit into the images width. It might need a lot of CPU time, but it's cool:

// Function to return an Array of Strings
// Arguments: String to be wrapped, maximum width in pixels of each line, font and fontsize
function imgwordwrap($s, $maxWidth, $font, $size) {
  // Make an empty ArrayList
  $a = array();
  $w = 0;    // Accumulate width of chars
  $i = 0;      // Count through chars
  $rememberSpace = 0; // Remember where the last space was
  // As long as we are not at the end of the String
  while ($i < strlen($s)) {
    // Current char
    $c = substr($s, $i, 1);
    $bb = imagepsbbox($c, $font, $size); // calculate width
    $w += abs($bb[3])-abs($bb[1]); // accumulate width
    if ($c == ' ') $rememberSpace = $i; // Are we a blank space?
    if ($w > $maxWidth) {  // Have we reached the end of a line?
      $sub = substr($s,0,$rememberSpace); // Make a substring
            // Chop off space at beginning
            if (substr($sub,0,1)==' ') $sub = substr($sub,1);
      // Add substring to the array
      $a[] = $sub;
      // Reset everything
      $s = substr($s,$rememberSpace);
      $i = 0;
      $w = 0;
    }
    else {
      $i++;  // Keep going!
    }
  }

  // Take care of the last remaining line
  trim($s);
  if (substr($s,0,1)==' ') $s = substr($s,1);
  $a[] = $s;

  return $a;
}
up
-1
honza dot bartos at gmail dot com
17 years ago
When using imagepsbbox, keep in mind, that meaning of y-coordinates is slightly different here. Y-coordinates returned by this function are related to the baseline of the text starting at point [0,0]. Positive values represent points ABOVE the baseline, negative values represent points BELOW the baseline. That is why the lower left y-coordinate is always smaller here than the upper right y-coordinate (these two coordinates are actualy values of metrics.descent and metrics.ascent - see T1Lib docs).

So when you want to place some text using coordinates of the top left corner (for example [100,100]), use this:

<?php

$x
= 100;
$y = 100;
$text = "Dodge this";
$fontsize=18;
$font=imagepsloadfont("somefont.pfb");
list(
$lx,$ly,$rx,$ry) = imagepsbbox($text,$font,$fontsize);
imagepstext ($someimage, $text, $font, $fontsize, $somecolor, $somecolor, $x, $y + $ry);

?>

Hope it helps someone, I got stuck with this for a while.
up
-1
daniel at dantec dot NO_SPAM dot nl
22 years ago
When using imagepsbbox, you are probably trying to do something like creating a button with text, so that the button is large enough for the text...
Below is a very simple example of making a black button just big enough to display white text on it.

<?php

//if text is no variable set sample text
if (!$text)
   
$text = "This is a sample text";
   
// set the font size
$fontsize=14;

// load the font to use
$font=ImagePsLoadFont("/fonts/ariam___.pfb");

//get the left lower corner and the right upper
list($lx,$ly,$rx,$ry) = imagepsbbox($text,$font,$fontsize,0,0,0);

// calculate the size of the text
$textwidth = $rx - $lx;
$textheight = $ry - $ly;

// make an image 40 pixels wider and 20 pixels higher than the text
$imh = $textheight + 20;
$imw = $textwidth + 40;
$im = imageCreate( $imw, $imh );

//define colors, first color is used as background color!
$black  = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);

//create the text (with the same parameters as imagepsbbox!)
ImagePSText ($im, "$text", $font, $fontsize, $white, $white, 20, 20,'','','',4);

//send the header
header("Content-type: image/jpeg");

// create the image
ImageJPEG ($im,"",100);

//destroy the image & font to free memory
Imagepsfreefont ( $font );
ImageDestroy ( $im );

?>
up
-1
eikie
15 years ago
in my code below, there is an error!

replace
$w += abs($bb[3])-abs($bb[1]); // accumulate width

with
$w += abs($bb[2])-abs($bb[0]); // accumulate width

also after
$bb = imagepsbbox($c, $font, $size); // calculate width

you can add this line because spaces make odd values...
if ($c == ' ' ) $bb = imagepsbbox('i', $font, $size);
To Top