PHP ImageMagick - Как центрировать внутреннюю линию и блок с автоматически выбранным размером шрифта - PullRequest
0 голосов
/ 17 января 2019

PHP 5.4. Приветствую вас, я применяю решение на основе source , в котором установлен текстовый блок и размер текста выбирается автоматически в зависимости от длины текста zip Теперь необходимо, чтобы текст находился по центру в указанном поле и строке, четко здесь на скриншотах, а также правильно поворачивал текст

скриншоты:

enter image description here

 function autofit_text_to_image( $canvas_image_filename = false, $dest_filename = 'output.jpg', $text = '', $starting_font_size = 60, $max_width = 500, $max_height = 500, $x_pos = 0, $y_pos = 0, $font_file = false,$font_color = 'black',$rotate = 0, $line_height_ratio = 1, $dest_format = 'jpg' ) {

// Bail if any essential parameters are missing
if ( ! $canvas_image_filename || ! $dest_filename || empty($text) || ! $font_file || empty($font_color) || empty($max_width) || empty($max_height) ) return false;

// Do we have a valid canvas image?
if ( ! file_exists($canvas_image_filename) ) return;

$canvas_handle = fopen( $canvas_image_filename, 'rb' );

// Load image into Imagick
$NewImage = new Imagick();
$NewImage->readImageFile($canvas_handle);

// Instantiate Imagick utility objects
$draw = new ImagickDraw();
$pixel = new ImagickPixel( $font_color );

// Load Font 
$font_size = $starting_font_size;
$draw->setFont($font_file);
$draw->setFontSize($font_size);
$draw->setFillColor($font_color);
//$draw->setFillColor('red');
// Holds calculated height of lines with given font, font size
$total_height = 0;

$countall=0;
// Run until we find a font size that doesn't exceed $max_height in pixels
while (( 0 == $total_height || $total_height > $max_height )) {
        $countall=$countall+1;

    if ( $total_height > 0 ) $font_size--; // we're still over height, decrement font size and try again

    $draw->setFontSize($font_size);

    // Calculate number of lines / line height
    // Props users Sarke / BMiner: /6096850/kak-mozhno-obernut-tekst-s-pomoschy-imagick-v-php-chtoby-on-risovalsya-kak-mnogostrochnyi-tekst

    //$words = preg_split('%\s%', $text, -1, PREG_SPLIT_NO_EMPTY);
    $words =preg_split( '%\s%', $text, -1, PREG_SPLIT_NO_EMPTY );

    $lines = array();
    $i = 0;
    $line_height = 0;
$one=1;


    while ( count($words) > 0 ) { 
        $one=$one+1;

        $metrics = $NewImage->queryFontMetrics( $draw, implode(' ', array_slice($words, 0, ++$i)));
        $line_height = max( $metrics['textHeight'], $line_height );


    if ( $metrics['textWidth'] > $max_width || count($words) < $i ) {
// this indicates long words and forces the font to decrease in the first loop
if($i == 1){
    $total_height = $max_height + 1;
    continue 2;
}
$lines[] = implode( ' ', array_slice($words, 0, --$i) );
$words = array_slice( $words, $i );
$i = 0;
}   

    }

    $total_height = count($lines) * $line_height * $line_height_ratio;

    if ( $total_height === 0 ) return false; // don't run endlessly if something goes wrong
}

// Writes text to image
for( $i = 0; $i < count($lines); $i++ ) {
    $NewImage->annotateImage( $draw, $x_pos, $y_pos + ($i * $line_height * $line_height_ratio), $rotate, $lines[$i] );  
}

$NewImage->setImageFormat($dest_format);
$result = $NewImage->writeImage($dest_filename);

return $result;
}

//The file on which we impose the image
$canvas_image_filename = 'test.jpeg';

$text = 'Lorem ipsum dolor sit amet, sed deleniti intellegebat cu, et ius molestiae abhorreant reprehendunt. Ex eius mollis adipiscing vix, audire theophrastus has et, malorum numquam sea et. 
Ut vel vidit falli, in error inermis argumentum per, et doctus necessitatibus vel. 
Ut has tota gloriatur, eum ad tale voluptua deserunt. Mel iriure deleniti forensibus at.';

// We load the font
$text ="Little text";
$font_file = 'Oswald-Regular.ttf';
$font_color = 'black';
//image

// Directory from the root
$dirfile='/home/xxxxx/xxxxxxx.com/htdocs/www/xxxx/';
$gimg=str_replace(".", "",microtime(TRUE)); 
if (!file_exists($dirfile.'test/')) {
if (!mkdir($dirfile.'test/', 0755, true)) {  die('Eror');}
}
$file_save=$dirfile.'test/'.$gimg.".jpg";
$result=autofit_text_to_image($canvas_image_filename, $file_save, $text, 60, 399, 290, 350, 128, $font_file,$font_color,0);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...