douhuangjie4503 2014-02-18 23:06
浏览 71
已采纳

php - 在多行上转换单行字符串,然后插入图像

I'm programming a script that inserts a text on an image, it works but not entirely, ie if a user adds a line break in the textarea is fine, but if all the text is on one line looks bad . This is my code

$str="this is a string inserted by an user";
$img_width= 500;
$img_height= 500;
$font_size = 1; 
$txt_max_width = intval(0.6 * $img_width);
do {
    $font_size++;
    $p = imagettfbbox($font_size,0,$font,$str);
    $txt_width=$p[2]-$p[0];
    } while ($txt_width <= $txt_max_width);
    $y = $img_height * 0.4;
$x = ($img_width - $txt_width) / 2;
$white = imagecolorallocate($img, 255, 255, 255);
imagettftext($img, $font_size, 0, $x, $y, $white, $font, $str);
imagepng($img);
imagedestroy($img);

Look at this for understand http://app.xskarx.com

PS: sorry for my bad english

  • 写回答

2条回答 默认 最新

  • dongmou2389 2014-02-19 01:18
    关注

    What you want to do, is to split the string into smaller block or chunks, for that, you have chunk_split in PHP.

    You will use it this way:

    // initialize variables
    $final_string = false;
    $size_of_the_chunk = 20;
    $str = "_this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string__this_is_a_very_long_string_";
    $length_of_string = strlen( $str );
    
    // work only if necessary
    if ( $length_of_string > $size_of_the_chunk ) {
        $final_string = chunk_split( $str, $size_of_the_chunk );
    } else {
        $final_string = $str;
    }
    

    The main problem you may have, is that the string will get split on random places, at least random from the perspective of the user, and so, the fragments may not make much sense. Try to improve the user interface by informing that they should use line breaks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改