目的:客户端上传图片,服务器接收并交至python处理。
1.一个简单的解决方案思维导图
2.PHP的socket客户端源码
<?php
$mypath = $_POST['path'];
set_time_limit(0);
$host="172.18.66.250";
print_r("path:".$mypath.";");
$port=8888;
$flag = 0x2;
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("cannot create socket\n");
$conn=socket_connect($socket,$host,$port) or die("cannot connect server\n");
if($conn){echo "client connect ok!";}
socket_write($socket,$mypath."+/opt/lampp/htdocs/imgWebserver/output") or die("cannot write data\n");
$buffer=socket_read($socket,1024);
echo "response was+".$buffer."response was+";
socket_close($socket);
?>
3.PHP的图片上传源码
<?php
//获取ajax传来的base64编码,$_POST['img']是你后台获取到的图片
$base64_image_content = $_POST['img'];
$name = $_POST['name'];
//图片保存的位置
$path= './upload/';
//这个是自定义函数,将Base64图片转换为本地图片并保存
$data = base64_image_content($base64_image_content,$path,$name);
#echo $data;
/**
* 将Base64图片转换为本地图片并保存
* @param $base64_image_content 要保存的Base64
* @param $path 要保存的路径
*/
function base64_image_content($base64_image_content,$path,$name){
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
//后缀
$type = $result[2];
//创建文件夹,以年月日
$new_file = $path."/";
if(!file_exists($new_file)){
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($new_file, 0700);
}
$new_file = $new_file.$name.".{$type}"; //图片名以时间命名
//保存为文件
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
//返回这个图片的路径
return $new_file;
}else{
return false;
}
}else{
return false;
}
}
4.python服务端源码
#-*- coding:utf-8 -*-
import sys
import os.path as osp
import socket
from optparse import OptionParser
def add_path(path):
if path not in sys.path:
sys.path.append(path)
this_dir=osp.dirname(__file__)
lib_path=osp.join(this_dir,'tools')
add_path(lib_path)
add_path(this_dir)
from test_my import testSingleImg
from CalculateDistArea import calculateDistArea
def runPredict(image_list,output):
(Area, averageDist,mask,mask1,t)=testSingleImg(image_list,output)
return Area, averageDist, t
if __name__ == "__main__":
# 创建tcp服务端socket
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定端口
tcp_server_socket.bind(("172.18.66.250", 8888))
# 设置监听,把服务端socket由主动套接字改成被动套接字,只能接收客户端的连接请求
tcp_server_socket.listen(128)
while True:
try:
print("开始监听.......")
client_socket, client_ip = tcp_server_socket.accept()
print("一个客户端连接上.....")
str_recive = client_socket.recv(1024)
if str_recive:
# print(str_recive)
data_str=str(str_recive)
print(data_str)
str1 = data_str.split("+")
str2 = str1[0]
str3 = str1[1]
print(str2)
print(str3)
Area,averageDist,t=runPredict(str2,str3)
#print('The area =%f and average distance =%f'%(Area, averageDist))
print Area, averageDist, t
client_socket.send(str(averageDist).encode("utf-8"))
str(averageDist).encode("utf-8").split("1")
else:
break
except Exception,e:
print e.message
client_socket.close()