这篇文章上次修改于 2866 天前,可能其部分内容已经发生变化,如有疑问可询问作者。

注:原创,转载请注明来处

运行环境:CentOs

需要的安装包:

GraphicsMagick,下载地址:ftp://ftp.graphicsmagick.org/pub/GraphicsMagick/

说明:

使用python做一个socket服务,主要功能就是调用GraphicsMagick命令生成指定大小的图片。

python脚本:

#coding=utf-8
__author__ = 'yangzhiwu'
import os,commands,re,socket,threading
import time,Queue,json,logging
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
'''
    任务线程
'''
class TaskThread(threading.Thread):
    '''
        初始化
    '''
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self.queue = queue
    '''
     执行线程
    '''
    def run(self):
        data = self.queue.get() #取出一项任务
        data = data.split('|')
        self.thumbImg( data[0], int(data[1]), int(data[2]) )
        self.queue.task_done() #完成任务信号
    '''
        做任务
    '''
    #生成缩略图的方法
    def thumbImg( self, src_img, t_width, t_height  ) :
        src_img='/data/www/wwwroot/picture/%s' % src_img
        saveImg='%s_%s_%s.jpg' % (src_img,t_width,t_height)
        info_cmd='/usr/local/graphicsmagick/bin/gm identify  %s' % src_img
        #print  info_cmd
        (status, info) = commands.getstatusoutput(info_cmd)
        #get image width and height
        match=re.findall(r'(\d+)x(\d+)', info)
        if not match :
            print("no image")
            return
        y_width=int( match[0][0] )
        y_height=int( match[0][1] )
        if y_width < t_width :
            t_width = y_width
        if y_height < t_height :
            t_height = y_height
        cmd='/usr/local/graphicsmagick/bin/gm convert %s -thumbnail "%sx%s^" -gravity center -extent %sx%s %s' % (src_img,t_width,t_height,t_width,t_height,saveImg)
        (status, result) = commands.getstatusoutput(cmd)
        logging.info('Time : %s ' % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) )
        logging.info('Info cmd:%s' % info_cmd )
        logging.info('img info:%s' % info )
        logging.info('cmd:%s | status:%s' % (cmd,status) )
        logging.info('================================================================================================================================================================================')
'''
'''
#主方法
def main() :
    #创建tcp socket
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind(("127.0.0.1", 9555))
    s.listen(5)
    #创建队列
    queue=Queue.Queue()
    log_file_handler = TimedRotatingFileHandler(filename="/data/python/thumb.log", when="D", interval=1, backupCount=10)
    #log_filename="/data/python/thumb.log"
    #logging.basicConfig(filename=log_filename, filemode='w', level=logging.INFO)
    logging.basicConfig(level=logging.INFO)
    log = logging.getLogger()
    log.addHandler(log_file_handler)
    while True :
        client,addr = s.accept()#连接
        data = str(client.recv(1024))
        client.close()
        logging.info('recv info :%s' % data )
        if data :
            data=data.split('::')
            #将任务写入到队列中
            for i in data :
                queue.put(i)
            #开始线程
            for i in data:
                t = TaskThread(queue)
                t.setDaemon(True) #子线程随主线程一起退出
                t.start() #启动线程
                t.join(10) #保证每个线程运行,但只等10s
            queue.join() #等所有任务都处理后,再退出
if __name__ == '__main__':
    main()

php使用的列子:

header ( 'Content-type:text/html;charset=utf8' );
$host = 'tcp://127.0.0.1:9555';
$fp = stream_socket_client ( $host, $errno, $error, 20 );
if (! $fp){
    echo "$error ($errno)";
} else{
    fwrite ( $fp, '2017/01/12/5876e965071ae.jpg|200|130::2017/01/12/5876e965071ae.jpg|200|80' );
    fclose ( $fp );
}