带有文本的GIF会导致文本质量下降

时间:2018-12-17 15:48:17

标签: php laravel gif countdown

我需要有关PHP函数“ imagettftext”当前遇到的问题的指导。我正在尝试从白色背景PNG图像创建GIF倒计时并将倒计时文本添加到其中。但是,文本没有获得所需的(黑色)颜色,并且像素化程度很高。

如何创建质量良好的倒计时GIF?

我的代码在这里:

    date_default_timezone_set('Europe/Copenhagen');
    $future_date = new DateTime($end_date);
    $time_now = time();
    $now = new DateTime(date('r', $time_now));
    $frames = array();
    $delays = array();
    $imgUrl = \URL::to('assets/gif/countdown/countdown.png');
    $image = imagecreatefrompng($imgUrl);
    $delay = 100; // milliseconds
    $font = array(
        'size' => 50,
        'angle' => 0,
        'x-offset' => 100,
        'y-offset' => 300,
        'file' => __DIR__ . '/../../../public/assets/gif/countdown/Quicksand-Bold.ttf',
        'color' => imagecolorallocate($image, 0, 0, 0),
    );
    for($i = 0; $i <= 60; $i++){
        $interval = date_diff($future_date, $now);
        if($future_date < $now){
            // Open the first source image and add the text.
            $image = imagecreatefrompng($imgUrl);
            $text = $interval->format('00:00:00:00');
            imagettftext($image , $font['size'] , $font['angle'] , $font['x-offset'] , $font['y-offset'] , $font['color'] , $font['file'], $text );
            imagealphablending($image, false);
            imagesavealpha($image, true);
            ob_start();
            imagegif($image);
            $frames[] = ob_get_contents();
            $delays[] = $delay;
            $loops = 1;
            ob_end_clean();
            break;
        } else {
            // Open the first source image and add the text.
            $image = imagecreatefrompng($imgUrl);
            $text = $interval->format('%aD %HH %IM %SS');
            // %a is weird in that it doesn’t give you a two digit number
            // check if it starts with a single digit 0-9
            // and prepend a 0 if it does
            if(preg_match('/^[0-9]\:/', $text)){
                $text = '0'.$text;
            }
            imagettftext ($image , $font['size'] , $font['angle'] , $font['x-offset'] , $font['y-offset'] , $font['color'] , $font['file'], $text );
            imagealphablending($image, false);
            imagesavealpha($image, true);
            ob_start();
            imagegif($image);
            $frames[] = ob_get_contents();
            $delays[] = $delay;
            $loops = 0;
            ob_end_clean();
        }
        $now->modify('+1 second');
    }
    //expire this image instantly
    header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
    header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
    header( 'Cache-Control: no-store, no-cache, must-revalidate' );
    header( 'Cache-Control: post-check=0, pre-check=0', false );
    header( 'Pragma: no-cache' );
    $gif = new GifEncoder($frames, $delays, $loops);
    $gif->display();

哪个给我这个结果: GIF example

0 个答案:

没有答案