接到朋友的需求,朋友是做php的,让我帮忙处理php生成gif的需求。他的项目类似抖音短视频那种,就是展示出来的界面是gif动图,然后点进去是完整的视频。
我想了想,我倒是没做过php生成gif的需求啊。但是python能做啊,满打满算,核心代码几行就能搞定了。那我为何我不给他写个外挂程序呢
这里用到了moviepy 这个包。
1.安装moviepy:
pip install moviepy
2.写程序开始。
在他的服务器上我很快就配好了python 和 pip的环境。
#!usr/bin/env python #-*- coding:utf-8 _*- """ @author:Hurrican @file: gif.py @time: 2019/06/22 21:33 """ import sys import moviepy.editor as mpy imge_url=sys.argv[1] if imge_url !='': '''处理路径start''' piece = imge_url.split('/')[-2:] path = '/'.join(piece) path = path.replace('.mp4','.gif') dirname = '/usr/share/nginx/html/KY/data/upload/'+path '''处理路径end''' try: #视频文件的本地路径 content = mpy.VideoFileClip(imge_url) # 剪辑0分0秒到0分1秒的片段。注意:不使用resize则不会修改清晰度 c1 = content.subclip((0,0),(0,1)).resize((480,320)) c1.write_gif(dirname) except Exception as e: print(e) else: print('系统错误')
上面是我写的python 代码。
大家可能注意到了。,sys.argv[1],其实这个是我从php传过来的参数。
给你们拓展下:
引入 sys模块。sy.argv[1]就到表从php传过来的第一个参数
下面是php代码,我截取片段,
php代码
<?php // +---------------------------------------------------------------------- // | YFCMF [ WE CAN DO IT MORE SIMPLE ] // +---------------------------------------------------------------------- // | Copyright (c) 2015-2016 http://www.rainfer.cn All rights reserved. // +---------------------------------------------------------------------- // | Author: rainfer <81818832@qq.com> // +---------------------------------------------------------------------- namespace app\home\controller; use think\Cache; use think\Db; use think\captcha\Captcha; class Index extends Base { public function index() { set_time_limit(0); $news = DB::name('news')->order("news_time asc")->field('n_id,news_title,news_time,news_content,news_hits,member_list_id,news_hits,zan_num')->select(); $data = [ 'news' => $news, ]; #########################################################外挂开始########################################################## foreach ($data['news'] as $key => $value) { # code... $img_url = $value['news_content']; if($img_url!=''){ $order = "python ".getcwd()."/app/home/controller/gif.py {$img_url}"; $data = shell_exec($order); var_dump($data); // // $result = exec('/usr/bin/python /usr/share/nginx/html/KY/app/home/controller/gif.py {$img_url}'); // #写日志文件 file_put_contents(dirname(__FILE__).'/log.txt', $data.'\r\n',FILE_APPEND); } }
#########################################################外挂结束##########################################################
// echo '<pre>';
// print_r($data);die;
return $this->view->fetch(':index');
}
中间标识的外挂就是我将php与pyhon交互的代码。
这里我用到了 php的shell_exec 函数,之所以不用exec是因为它只能返回一行结果。而shell_exec可以返回全部结果。 getcwd()是php的一个函数,标识返回当前工作目录
python 双引号里面记得还要留个空格哦。然后可以打印出结果。然后在php项目里面加个日志文件就行了。
成功后,我们来看看日志文件长什么样:
下面是工作目录。本次采用YFCMF的TP框架。但是一定要注意要给777 权限(644好像不行,测试失败了),不然写不了日志文件。