接到朋友的需求,朋友是做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好像不行,測試失敗了),不然寫不了日志文件。