最近在折腾AI应用开发做了个电商详情图生成的小工具效果还不错今天来分享一下整个开发过程和踩过的坑。为什么要做这个做电商的朋友应该都懂详情图真的太重要了。一个产品要拍好几个角度还要P图、排版、加文案找设计师一张图至少几十块自己做又费时间。我就想能不能用AI来解决这个问题现在AI绘图技术已经很成熟了像nano banana 这些生成的图片质量已经很高了。关键是要保证同一个商品在不同场景下外观保持一致这个才是难点。核心功能设计我的思路是这样的上传商品参考图用户传几张商品实拍图最多5张AI提取商品特征通过视觉模型提取商品的核心特征场景描述用户可以自定义风格比如高端极简风格、户外使用场景等批量生成一次生成多张不同场景的详情图技术实现1. 图片上传模块这块比较简单支持拖拽和粘贴上传fromfastapiimportFastAPI,UploadFile,FilefromtypingimportListimportshutilfrompathlibimportPath appFastAPI()app.post(/upload-images)asyncdefupload_product_images(files:List[UploadFile]File(...)):上传商品参考图最多5张iflen(files)5:return{error:最多只能上传5张图片}saved_files[]forfileinfiles:# 保存到临时目录file_pathPath(fuploads/{file.filename})withfile_path.open(wb)asbuffer:shutil.copyfileobj(file.file,buffer)saved_files.append(str(file_path))return{files:saved_files,count:len(saved_files)}2. 商品特征提取这是核心部分我用的是OpenAI的Vision API来提取商品特征importopenaiimportbase64defextract_product_features(image_path:str)-dict:提取商品的核心特征withopen(image_path,rb)asimage_file:base64_imagebase64.b64encode(image_file.read()).decode()responseopenai.ChatCompletion.create(modelgpt-4-vision-preview,messages[{role:user,content:[{type:text,text:请详细描述这个商品的外观特征包括颜色、材质、形状、细节等用于后续AI生成时保持一致性。},{type:image_url,image_url:{url:fdata:image/jpeg;base64,{base64_image}}}]}],max_tokens500)return{description:response.choices[0].message.content,features:parse_features(response.choices[0].message.content)}3. 详情图生成这里我用了Stable Diffusion的API结合提取的商品特征和用户的场景描述importrequestsfromtypingimportOptionaldefgenerate_detail_images(product_features:str,scene_prompt:Optional[str]None,count:int5,aspect_ratio:str3:4,resolution:str1K)-List[str]:生成电商详情图# 构建完整的promptbase_promptfProduct photography,{product_features}ifscene_prompt:full_promptf{base_prompt},{scene_prompt}else:# AI自动策划场景full_promptf{base_prompt}, professional e-commerce style, clean background# 设置分辨率resolution_map{0.5K:(512,683),1K:(1024,1365),2K:(2048,2731),4K:(4096,5461)}width,heightresolution_map.get(resolution,(1024,1365))generated_images[]foriinrange(count):# 调用SD APIresponserequests.post(sdapi/v1/txt2img,json{prompt:full_prompt,negative_prompt:low quality, blurry, distorted,width:width,height:height,steps:30,cfg_scale:7,sampler_name:DPM 2M Karras})ifresponse.status_code200:image_dataresponse.json()[images][0]# 保存图片image_pathfgenerated/product_{i1}.pngwithopen(image_path,wb)asf:f.write(base64.b64decode(image_data))generated_images.append(image_path)returngenerated_images4. 价格计算根据不同分辨率计算费用defcalculate_cost(count:int,resolution:str)-float:计算生成费用price_map{0.5K:0.11,1K:0.17,2K:0.17,4K:0.30}unit_priceprice_map.get(resolution,0.17)returnround(count*unit_price,2)# 示例costcalculate_cost(count5,resolution1K)print(f预估费用¥{cost})# 输出¥0.85实际效果测试下来效果还是挺惊艳的一致性保持得不错同一个商品在不同场景下外观基本一致生成速度快1K分辨率的图大概10秒一张成本可控比找设计师便宜太多了未来优化方向支持更多风格模板预设一些常见的电商风格批量处理一次上传多个商品批量生成智能抠图自动把商品从背景中抠出来文案生成AI自动生成商品卖点文案总结做这个工具最大的感受是AI真的能解决实际问题。不需要多高深的技术把现有的API组合好就能做出有价值的产品。