How can I wrap text using Imagick in PHP so that it is drawn as multiline text?

前端 未结 5 1500
悲哀的现实
悲哀的现实 2020-12-05 16:54

The Imagick library in PHP allows you to draw text on top of an image.

How can I tell Imagick to wrap the text based upon some bounded text box, so that the words ap

5条回答
  •  鱼传尺愫
    2020-12-05 17:38

    here is my version for one line text container

    function GetTextSize($font,$text,$max_weight,$max_width){
    $size = $max_weight;
    $imagick=new Imagick();
    while (true){
        $draw = new ImagickDraw();
        $draw->setFontSize($size);
        $draw->setfont($font);
        $bbox2=$imagick->queryFontMetrics($draw,$text);
        $width_of_text = $bbox2[textWidth];
        if ($width_of_text > $max_width){
            $size -= 1;
        }else{
            break;
            }
        }
        return $size;
    }
    $draw = new ImagickDraw();
    $font="path_to_font.ttf";
    $text="Love Happyness Freedom";
    $output = new Imagick('path_to_image.jpg');
    $output->setGravity(Imagick::GRAVITY_CENTER);
    $fontsize=GetTextSize($font,$text,70,600);
    $draw->setfont($font);
    $draw->setFontSize($fontsize);
    $draw->annotation(000, 000, $text);
    $output->drawImage($draw);
    $output->setImageFormat('jpg');
    header('Content-Type: image/jpg');
    print $output;
    

提交回复
热议问题