PHP.mk документација

imageftbbox

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.imageftbbox.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.imageftbbox.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
imageftbbox

Референца за `function.imageftbbox.php` со подобрена типографија и навигација.

function.imageftbbox.php

imageftbbox

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imageftbbox(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

= NULL

imageftbbox(
         float $size,
         float $angle,
         string $font_filename,
         string $string,
         array $options = []
): array|false

Дајте ја границата на текст користејќи фонтови преку freetype2

Забелешка:

за пишување (оставјајќи го стрингот недопрен). imageftbbox() беше проширена варијанта на imagettfbbox() што дополнително го поддржуваше optionsКако на PHP 8.0.0, imagettfbbox() е псевдоним за imageftbbox().

Параметри

size

Големината на фонтот во точки.

angle

Агол во степени во кој string ќе се мери.

font_filename

Оваа функција пресметува и враќа граница во пиксели за FreeType текст.

string

Низата што треба да се измери.

options

Текст што треба да се вметне во сликата. options
Можни индекси на низи за Тип Значење
linespacing float Клуч

Вратени вредности

imageftbbox() Името на TrueType фонт датотеката (може да биде URL). Во зависност од верзијата на GD библиотеката што ја користи PHP, може да се обиде да бара датотеки што не започнуваат со водечка '/' со додавање на '.ttf' на името на датотеката и пребарување по патека дефинирана од библиотеката.

0 долниот лев агол, X позиција
1 долниот лев агол, Y позиција
2 долниот десен агол, X позиција
3 долниот десен агол, Y позиција
4 горниот десен агол, X позиција
5 горниот десен агол, Y позиција
6 горниот лев агол, X позиција
7 горниот лев агол, Y позиција

Точките се релативни во однос на text независно од angle, така што 'горниот лев' значи во горниот лев агол гледајќи го текстот хоризонтално.

При неуспех, false се враќа.

Примери

Пример #1 imageftbbox() example

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');

// Output to browser
header('Content-Type: image/png');

imagepng($im);
?>

Белешки

Забелешка: Враќа низа со 8 елементи што претставуваат четири точки што ја прават границата на текстот. Редоследот на точките е долна лева, долна десна, горна десна, горна лева. Точките се релативни на текстот без оглед на аголот, така што "горна лева" значи во горниот лев агол кога текстот го гледате хоризонтално. ВраќаОвој примерок скрипта ќе произведе бела PNG 400x30 пиксели, со зборовите "Testing..." во црно (со сива сенка), во фонтот Arial.)

Види Исто така

  • imagefttext() --with-freetype-dir=DIR
  • imagettfbbox() Оваа функција е достапна само ако PHP е компајлиран со поддршка за freetype (

Белешки од корисници 8 белешки

fernando
20 години пред
imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text: 

0 lower left corner, X position 
1 lower left corner, Y position 
2 lower right corner, X position 
3 lower right corner, Y position 
4 upper right corner, X position 
5 upper right corner, Y position 
6 upper left corner, X position 
7 upper left corner, Y position 

The points are relative to the text regardless of the angle, so "upper left" means in the top left-hand corner seeing the text horizontally.
враќа низа со 8 елементи што претставуваат четири точки што ја прават границата на текстот:
пред 23 години
This function can be used to generate right-aligned text. Just work out how wide the text image is and position it accordingly. Example:

$i_width  = 200;
$i_height = 40;

$string = "Hello World!";
$pointsize = 10;
$fontfile = "/usr/local/lib/ttf/Helve.ttf";

$im = imagecreate($i_width, $i_height);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);

$string_size = ImageFtBbox($pointsize, 0, $fontfile, $string, array("linespacing" => 1));
$s_width  = $string_size[4];
$s_height = $string_size[5];

ImageFtText($im, $pointsize, 0, $i_width - $s_width - 1,  0 - $s_height, $white, $fontfile, $string, array("linespacing" => 1));

Header ("Content-type: image/png");
ImagePNG ($im);
ImageDestroy ($im);
phpimageftbbox на juggernaut точка com точка au
21 години пред
Here is a handy example I used to center "dynamic text" onto an image.  

Ex. Say you want to center a clients IP Address onto a picture.  

$ip=$_SERVER['REMOTE_ADDR'];    

$details = imageftbbox($fontsize, 0, $font, $ip, array("linespacing" => 1));

$xcoord = ($imgwidth - $details[4]) / 2;  // this will return the x coordinate centered to your specific image.  Make sure  you set $imgwidth to the width of the image you are using.      

imagettftext($image, $fontsize, 0, $xcoord, $ycoord, $fontcolor, $font, $ip);
sectionthirty1 на yahoo точка com
20 години пред
ah... the problem between imageftbbox() and imagefttext() lies in the mirroring of the y-axes.
Below you see, for a font-size 16 the boudingboxes of "b", "p" and "bp":
< b: w=9 h=15
b(0,-1)
b(9,-1)
b(9,-16)
b(0,-16)
< p: w=9 h=16
p(0,4)
p(9,4)
p(9,-12)
p(0,-12)
< bp: w=20 h=20
bp(0,4)
bp(20,4)
bp(20,-16)
bp(0,-16)
If drawing "bp" using imagefttext() at y=0, the the top of "bp" indeed is at y=-16, and the bottom of "bp" at y=4. (Plus or minus a pixel here and there, because at y=0 there actually is a vissible pixel.)
theo v e -2
пред 8 години
//EXAMPLE - Center text

function newText($im, $size, $angle= 0, $x, $y, $color, $font, $text,$align = "left",$border=false,$width=0,$height=0){
    
    if($align == "center")
    {
        if ($border == true ){
           imagerectangle($im, $x, $y, $x +$width, $y + $height, $color);
        }
        $bbox = imageftbbox($size, 0, $font, $text);

        // Marcamos el ancho y alto
        $s_width  = $bbox[4];
        $s_height = $bbox[5];  
        
        $y = $y + ($height-$s_height)/2;
        $x = $x + ($width-$s_width)/2;

    }
     
    imagettftext($im, $size, $angle, $x, $y, $color, $font, $text);
}
Јохан
пред 18 години
For alignment i used this method:

if($align == "center" || $align == "right")
    {
        $verticaltxtspace = $backwidth - (2 * $posx);        
        $spacepositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", " ");         
        $spacepx = $spacepositions[4] - $spacepositions[0];        
        
        // Split text in lines
        $lines = split("[\r][\n]", $text);        
        for($count = 0; $count < count($lines); $count++)
        {
            $textpositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", $lines[$count]);            
            $textpx = $textpositions[2] - $textpositions[0];
            
            if($align == "right")
            {
                $spaces = ($verticaltxtspace - $textpx) / $spacepx;
            }
            else if($align == "center")
            {
                $spaces = (($verticaltxtspace - $textpx)/2) / $spacepx;
            }
            
            // Add spaces
            $line = $lines[$count];
            for($i = 0; $i < $spaces; $i++)
            {
                $line = " " . $line;
            }
            $lines[$count] = $line;
        }
        
        // Create new text of lines
        $text = "";
        for($count = 0; $count < count($lines); $count++)
        {
            $text .= $lines[$count] . "\r\n";
        }        
    }
    
        
    //    Draw the shadow text on de shadow
    imagettftext($background, $size, $angle, $posx, $posy, $textcolor, "fonts/verdanaz.ttf",  $text);
pablocorezzola на gmail точка com
пред 23 години
i've found a work around for this situation

it seems that height is directly proportional to line spacing so you just have to apply the same factor to image height

for example :

$spacing = 0.7;
$params = array("linespacing" => $spacing);

$box = imageftbbox ($size, 0, $font, $text, $params);
$tw=$box[4]-$box[0]; //image width
$th=($box[1]-$box[5])*$spacing; //image height
ta на NOSPAM точка magicsquare точка info
21 години пред
ImageFTBBox returns a bounding box, not metrics, as some (most?) of the notes above seem to assume. The 8 values it returns specify the 4 corners of this bounding box. So to properly determine the width and height of a string you need to do:

$bbox = ImageFTBBox(...);
$width = abs($bbox[0]) + abs($bbox[2]); // distance from left to right
$height = abs($bbox[1]) + abs($bbox[5]); // distance from top to bottom
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.