zoukankan      html  css  js  c++  java
  • php 实现将文本、图片写到同一张图上面以及文本的自动换行

    以laravel框架为例:

    首先controller中引用ImageManager;

    use InterventionImageImageManager;

    下面就是关键处理,

      

    $date = date('Y年m月d日 H:i', $data['time']);
    $title = $data['title'];
    $content = $data['content'];
    $id = $data['id'];
    //原图地址-画布
    $dir = env('UPLOAD_FILE_ORIGINAL_DIR', 'Thumb') . '/' .env('UPLOAD_FILE_TEMP_DIR', 'Temp');
    $baseImage = 'news_base.png';
    $baseFile = public_path($dir.'/'.$baseImage);

    //生成图片地址
    $shareImage = $dir.'/' .$id. '.png';
    $shareFile = public_path($shareImage);

    //插入画布的图片
    $img = public_path($img);

    //图片处理方法类
    $manager = new ImageManager();
    $fontTtf = public_path('fonts/DroidSansFallback.ttf');

    $image = $manager->make($baseFile)
    //insert text
    ->text($date, 219, 384, function ($font) {
    $font->file($fontTtf);
    $font->size(30);
    $font->color('#FCA969');
    $font->align('left');
    });
    //这个部分尤为重要:当文本中出现数字时,根据字符串长度换行,行末会出现多余空格,所以决定用下面的这种根据宽度实现自动换行
    function autowrap($fontsize, $angle, $fontface, $string, $width) {
    // 参数分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
    $content = "";
    // 将字符串拆分成一个个单字 保存到数组 letter 中
    preg_match_all("/./u", $string, $arr);
    $letter = $arr[0];
    foreach($letter as $l) {
    $teststr = $content.$l;
    $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
    if (($testbox[2] > $width) && ($content !== "")) {
    $content .= PHP_EOL;
    }
    $content .= $l;
    }
    return $content;
    }

    $i=577; //top
    $box = autowrap(30, 0, $fontTtf, $title, $i);

    $image = $image->text($box, 113, $i, function ($font) {
    $font->file(public_path('fonts/DroidSansFallback.ttf'));
    $font->size(34);
    $font->color('#222222');
    $font->align('top');
    });

    //insert content
    $i=715; //top
    $box = autowrap(30, 0, $fontTtf, $content, $i);
    $image = $image->text($box, 117, $i, function ($font) {
    $font->file(public_path('fonts/DroidSansFallback.ttf'));
    $font->size(30);
    $font->color('#666666');
    $font->align('top');
    });

    //insert img
    $image = $image->insert($img, 'bottom-left', 115, 450);

    $image->save($shareFile);

    好了!到这里就实现了,如果你中间也遇到自动换行效果不是很好的时候,就好好看看标红的部分找找原因吧~~
  • 相关阅读:
    vue 组件通信(全)
    clickoutside 代码实现
    reset css 样式重置
    vue computed 无法deep的问题
    sessionStorage的总结
    Windows系统maven安装配置
    Windows系统JDK安装配置
    开篇
    JIT即时编译器
    CLR基础
  • 原文地址:https://www.cnblogs.com/a-record/p/9233125.html
Copyright © 2011-2022 走看看