引言
现在照相馆越来越少了,拍摄证件照越来越贵了,还好我也打印机,还好我是个程序员
需求分析
使用百度人像分割技术,先将人像抠出开,在写入相对应的背景图片中即可
上代码
*首先我们使用百度人像分割 文档地址:https://ai.baidu.com/tech/body/seg
static void Main(string[] args)
{
// 设置APPID/AK/SK
var APP_ID = "百度appID";
var API_KEY = "百度API_KEY ";
var SECRET_KEY = "百度SECRET_KEY ";
var client = new Baidu.Aip.BodyAnalysis.Body(API_KEY, SECRET_KEY);
client.Timeout = 60000; // 修改超时时间
var image = File.ReadAllBytes(@"图片地址");
// 调用人像分割,可能会抛出网络等异常,请使用try/catch捕获
var result = client.BodySeg(image);
UploadImageByBase64String(result["foreground"].ToString());
Console.ReadKey();
}
将Base64位码保存成图片,并替换底色
public static void UploadImageByBase64String(string imgStr)
{
var result="";
try
{
byte[] bt = Convert.FromBase64String(imgStr);//获取图片base64
string fileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();//年月
string ImageFilePath = Directory.GetCurrentDirectory()+"/Image" + "/" + fileName;
if (!System.IO.Directory.Exists(ImageFilePath))//如果不存在就创建文件夹
{
System.IO.Directory.CreateDirectory(ImageFilePath);
}
string ImagePath = ImageFilePath + "/" + System.DateTime.Now.ToString("yyyyHHddHHmmss");//定义图片名称
File.WriteAllBytes(ImagePath + ".png", bt); //保存图片到服务器,然后获取路径
result = ImagePath + ".png";//获取保存后的路径
Image Imageimage;
Imageimage = System.Drawing.Image.FromFile(result);
Bitmap bitmap = new Bitmap(Imageimage);
// bitmap.MakeTransparent(Color.Red);
int width = bitmap.Size.Width;
int height = bitmap.Size.Height;
string ImagePath3 = ImageFilePath + "/" + System.DateTime.Now.ToString("yyyyHHddHHmmss") + "-33-.png";//定义图片名称
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
SolidBrush b = new SolidBrush(Color.Yellow);//这里修改颜色
g.FillRectangle(b, 0, 0, 300, 300);
g.DrawImage(Imageimage, 0, 0);
bmp.Save(ImagePath3);
}
catch (Exception e)
{
throw e;
}
Console.WriteLine(result);
}