save code
This commit is contained in:
Binary file not shown.
+147
@@ -131,6 +131,66 @@ def change_hair():
|
||||
'message': f'处理图片失败: {str(e)}'
|
||||
}), 500
|
||||
|
||||
@app.route('/api/change-hair-color', methods=['POST'])
|
||||
def change_hair_color():
|
||||
"""
|
||||
更换头发颜色
|
||||
接收用户上传的图片、颜色值和更换比例,调用远程API处理
|
||||
"""
|
||||
try:
|
||||
# 检查是否有文件上传
|
||||
if 'image' not in request.files:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '请上传图片'
|
||||
}), 400
|
||||
|
||||
# 获取图片文件、颜色值和更换比例
|
||||
image_file = request.files['image']
|
||||
rgb = request.form.get('rgb')
|
||||
ratio = request.form.get('ratio')
|
||||
|
||||
if not rgb:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '请选择颜色'
|
||||
}), 400
|
||||
|
||||
if not ratio:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '请设置更换比例'
|
||||
}), 400
|
||||
|
||||
# 验证文件类型
|
||||
if not allowed_file(image_file.filename):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': '不支持的文件类型,请上传图片文件'
|
||||
}), 400
|
||||
|
||||
# 读取图片数据
|
||||
image_data = image_file.read()
|
||||
|
||||
# 调用远程API处理图片
|
||||
result_image = call_remote_hair_color_api(image_data, rgb, ratio)
|
||||
|
||||
# 将处理后的图片转换为base64格式返回
|
||||
result_base64 = base64.b64encode(result_image).decode('utf-8')
|
||||
result_data_url = f'data:image/jpeg;base64,{result_base64}'
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'data': {
|
||||
'result_image': result_data_url
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'message': f'处理图片失败: {str(e)}'
|
||||
}), 500
|
||||
|
||||
def allowed_file(filename):
|
||||
"""
|
||||
验证文件类型是否允许
|
||||
@@ -226,6 +286,93 @@ def call_remote_api(image_data, hairstyle_id):
|
||||
# 如果远程API调用失败,返回原始图片
|
||||
return image_data
|
||||
|
||||
def call_remote_hair_color_api(image_data, rgb, ratio):
|
||||
"""
|
||||
调用远程头发颜色更换API
|
||||
根据用户提供的接口文档实现
|
||||
"""
|
||||
try:
|
||||
# 将图片数据转换为base64格式
|
||||
encoded_string = base64.b64encode(image_data).decode('utf-8')
|
||||
img64_str = f"data:image/jpeg;base64,{encoded_string}"
|
||||
|
||||
# 解析rgb参数
|
||||
rgb_list = list(map(int, rgb.strip('[]').split(',')))
|
||||
|
||||
# 构建请求数据(根据用户提供的格式)
|
||||
data = {
|
||||
"img": img64_str,
|
||||
"userId": "18701620166",
|
||||
"rgb": rgb_list,
|
||||
"ratio": float(ratio),
|
||||
"output_format": "base64"
|
||||
}
|
||||
|
||||
# 打印传入的参数(只打印部分信息,避免日志过长)
|
||||
print("=== 调用远程头发颜色更换API参数 ===")
|
||||
print(f"userId: {data['userId']}")
|
||||
print(f"rgb: {data['rgb']}")
|
||||
print(f"ratio: {data['ratio']}")
|
||||
print(f"output_format: {data['output_format']}")
|
||||
print(f"img 长度: {len(img64_str)}")
|
||||
print(f"img 前缀: {img64_str[:50]}...") # 只打印前缀
|
||||
print("====================")
|
||||
|
||||
# 设置请求头(根据用户提供的格式)
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
|
||||
# 发送请求到远程API
|
||||
print(f"发送请求到: {app.config['REMOTE_HAIR_COLOR_API_URL']}")
|
||||
response = requests.post(
|
||||
app.config['REMOTE_HAIR_COLOR_API_URL'],
|
||||
headers=headers,
|
||||
json=data,
|
||||
timeout=app.config['API_TIMEOUT']
|
||||
)
|
||||
|
||||
# 打印响应状态
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
print(f"响应内容长度: {len(response.text)}")
|
||||
# 只打印响应内容的前100个字符,避免base64数据过长
|
||||
response_text = response.text
|
||||
if len(response_text) > 100:
|
||||
print(f"响应内容: {response_text[:100]}...")
|
||||
else:
|
||||
print(f"响应内容: {response_text}")
|
||||
|
||||
# 解析响应数据
|
||||
response_data = response.json()
|
||||
|
||||
# 检查响应状态
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"远程API返回错误: {response_data.get('msg', '未知错误')}")
|
||||
|
||||
# 检查是否有数据返回(根据日志,远程API返回的是'result'字段而不是'data'字段)
|
||||
result_base64 = response_data.get('result', '')
|
||||
|
||||
if not result_base64:
|
||||
# 如果没有'result'字段,检查是否有其他错误信息
|
||||
error_msg = response_data.get('msg', '未知错误')
|
||||
raise Exception(f"远程API返回错误: {error_msg}")
|
||||
|
||||
# 打印成功信息
|
||||
success_msg = response_data.get('msg', '成功')
|
||||
print(f"远程API调用成功: {success_msg}")
|
||||
|
||||
# 移除可能的前缀
|
||||
if result_base64.startswith("data:image"):
|
||||
result_base64 = result_base64.split(",", 1)[1]
|
||||
|
||||
# 解码base64数据为图片
|
||||
result_image = base64.b64decode(result_base64)
|
||||
|
||||
print("远程API调用成功,返回处理后的图片")
|
||||
return result_image
|
||||
except Exception as e:
|
||||
print(f'调用远程API失败: {str(e)}')
|
||||
# 如果远程API调用失败,返回原始图片
|
||||
return image_data
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""
|
||||
|
||||
@@ -6,6 +6,9 @@ class Config:
|
||||
# 远程发型更换API地址
|
||||
REMOTE_API_URL = "http://xiangsilian.com:18801/api/swapHair/v1"
|
||||
|
||||
# 远程头发颜色更换API地址
|
||||
REMOTE_HAIR_COLOR_API_URL = "http://xiangsilian.com:18801/hairColor/v2"
|
||||
|
||||
# 远程API请求超时时间(秒)
|
||||
API_TIMEOUT = 120 # 延长超时时间,因为发型更换可能需要60秒
|
||||
|
||||
|
||||
Reference in New Issue
Block a user