引言
現(xiàn)在照相館越來越少了湿酸,拍攝證件照越來越貴了臼节,還好我也打印機,還好我是個程序員
需求分析
使用百度人像分割技術(shù)枣氧,先將人像摳出開,在寫入相對應(yīng)的背景圖片中即可
上代碼
*首先我們使用百度人像分割 文檔地址:https://ai.baidu.com/tech/body/seg
static void Main(string[] args)
{
// 設(shè)置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(@"圖片地址");
// 調(diào)用人像分割垮刹,可能會拋出網(wǎng)絡(luò)等異常达吞,請使用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))//如果不存在就創(chuàng)建文件夾
{
System.IO.Directory.CreateDirectory(ImageFilePath);
}
string ImagePath = ImageFilePath + "/" + System.DateTime.Now.ToString("yyyyHHddHHmmss");//定義圖片名稱
File.WriteAllBytes(ImagePath + ".png", bt); //保存圖片到服務(wù)器荒典,然后獲取路徑
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);
}