Beispiel #1
0
        public static void CopyMtl(string mtl, string newMtlName, string path, string subFolders, string projectPath)
        {
            var mtlPath = Path.Combine(path, mtl);
            var mtlFi   = new FileInfo(mtlPath);

            if (mtlFi.Exists)
            {
                var newMtlPath = Path.Combine(projectPath, subFolders, newMtlName);
                File.Copy(mtlPath, newMtlPath, true);

                var diffuseTextures = GetMtlibUsingItems(mtlPath);
                foreach (var texturePath in diffuseTextures)
                {
                    if (!File.Exists(texturePath))
                    {
                        continue;
                    }

                    var relativeTexturePath = texturePath.Remove(0, path.Length);
                    var newTexturePath      = relativeTexturePath.Replace("/", "\\");  // format of mtl
                    newTexturePath = newTexturePath.StartsWith("\\") ? newTexturePath.Remove(0, 1) : newTexturePath;
                    newTexturePath = Path.Combine(projectPath, subFolders, newTexturePath);
                    var textureFi = new FileInfo(newTexturePath);
                    if (texturePath != textureFi.FullName)
                    {
                        FolderEx.CreateDirectory(textureFi.Directory); // recreate folders structure
                        File.Copy(texturePath, textureFi.FullName, true);

                        using (var ms = new MemoryStream(File.ReadAllBytes(textureFi.FullName))) // Don't use using!!
                        {
                            var img = (Bitmap)Bitmap.FromStream(ms);
                            var max = Math.Max(img.Width, img.Height);
                            if (max > 1024)
                            {
                                var k      = 1024.0f / max;
                                var newImg = ImageEx.ResizeImage(img, new Size((int)(img.Width * k), (int)(img.Height * k)));
                                newImg.Save(textureFi.FullName, ImageFormat.Jpeg);
                            }
                        }
                    }
                }
            }
        }
Beispiel #2
0
        public void CreateProject()
        {
            #region Корректируем размер фотки

            var realTemplateImage = templateImage;
            using (var ms = new MemoryStream(File.ReadAllBytes(templateImage))) // Don't use using!!
            {
                var img = (Bitmap)Image.FromStream(ms);
                var max = (float)Math.Max(img.Width, img.Height);
                if (max != SelectedSize)
                {
                    var k      = SelectedSize / max;
                    var newImg = ImageEx.ResizeImage(img, new Size((int)Math.Round(img.Width * k), (int)Math.Round((img.Height * k))));

                    templateImage = UserConfig.AppDataDir;
                    FolderEx.CreateDirectory(templateImage);
                    templateImage = Path.Combine(templateImage, "tempProjectImage.jpg");

                    newImg.Save(templateImage, ImageFormat.Jpeg);
                }
            }

            #endregion

            var path = string.Empty;
            if (string.IsNullOrEmpty(textNewProjectFolder.Text))
            {
                path = UserConfig.AppDataDir;
                path = Path.Combine(path, "TempProject");
                FolderEx.CreateDirectory(path, true);
            }
            else
            {
                path = textNewProjectFolder.Text;
            }

            var projectName = string.IsNullOrEmpty(textNewProjectName.Text) ? "HeadShop project" : textNewProjectName.Text;
            ProgramCore.Project = new Project(projectName, path, templateImage, GenType, ManType, CustomModelPath, true, SelectedSize, fcr.IsOpenSmile);
            ProgramCore.Project.RealTemplateImage = realTemplateImage;

            ProgramCore.Project.FacialFeatures  = fcr.FacialFeatures;
            ProgramCore.Project.ImageRealPoints = fcr.RealPoints;

            ProgramCore.Project.LoadMeshes();

            var minX     = fcr.GetMinX();
            var topPoint = (TopEdgeTransformed.Y - ImageTemplateOffsetY) / ImageTemplateHeight;

            ProgramCore.Project.TopPoint.X = 0.0f;
            ProgramCore.Project.TopPoint.Y = topPoint;

            ProgramCore.Project.FaceRectRelative = new RectangleF(minX, topPoint, fcr.GetMaxX() - minX, fcr.BottomFace.Y - topPoint);
            ProgramCore.Project.MouthCenter      = new Vector2(fcr.LeftMouth.X + (fcr.RightMouth.X - fcr.LeftMouth.X) * 0.5f, fcr.LeftMouth.Y + (fcr.RightMouth.Y - fcr.LeftMouth.Y) * 0.5f);

            ProgramCore.Project.LeftEyeCenter  = fcr.LeftEyeCenter;
            ProgramCore.Project.RightEyeCenter = fcr.RightEyeCenter;
            ProgramCore.Project.FaceColor      = fcr.FaceColor;

            ProgramCore.Project.DetectedLipsPoints.Clear();
            ProgramCore.Project.DetectedNosePoints.Clear();
            ProgramCore.Project.DetectedBottomPoints.Clear();
            ProgramCore.Project.DetectedTopPoints.Clear();

            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[3]);            // точки рта
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[58]);
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[55]);
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[59]);
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[4]);
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[57]);
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[56]);

            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[61]); //Центр рта верх
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[64]); //Центр рта низ

            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[60]); //9
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[62]); //10

            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[63]); //11
            ProgramCore.Project.DetectedLipsPoints.Add(fcr.FacialFeatures[65]); //12


            ProgramCore.Project.DetectedNosePoints.Add(fcr.FacialFeatures[45]);           // точки носа
            ProgramCore.Project.DetectedNosePoints.Add(fcr.FacialFeatures[46]);
            ProgramCore.Project.DetectedNosePoints.Add(fcr.FacialFeatures[2]);
            ProgramCore.Project.DetectedNosePoints.Add(fcr.FacialFeatures[22]);
            ProgramCore.Project.DetectedNosePoints.Add(fcr.FacialFeatures[49]);

            ProgramCore.Project.DetectedLeftEyePoints.Add(fcr.FacialFeatures[23]); //Точки левого глаза
            ProgramCore.Project.DetectedLeftEyePoints.Add(fcr.FacialFeatures[28]);
            ProgramCore.Project.DetectedLeftEyePoints.Add(fcr.FacialFeatures[24]);
            ProgramCore.Project.DetectedLeftEyePoints.Add(fcr.FacialFeatures[27]);

            ProgramCore.Project.DetectedRightEyePoints.Add(fcr.FacialFeatures[25]); //Точки правого глаза
            ProgramCore.Project.DetectedRightEyePoints.Add(fcr.FacialFeatures[32]);
            ProgramCore.Project.DetectedRightEyePoints.Add(fcr.FacialFeatures[26]);
            ProgramCore.Project.DetectedRightEyePoints.Add(fcr.FacialFeatures[31]);

            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[5]); //точки нижней части лица
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[7]); // * 0.75f + fcr.FacialFeatures[9] * 0.25f);
            var p11 = fcr.FacialFeatures[11];
            ProgramCore.Project.DetectedBottomPoints.Add(new Vector3((p11.X + fcr.FacialFeatures[9].X) * 0.5f, p11.Y, fcr.FacialFeatures[9].Z));
            ProgramCore.Project.DetectedBottomPoints.Add(new Vector3((p11.X + fcr.FacialFeatures[10].X) * 0.5f, p11.Y, fcr.FacialFeatures[10].Z));
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[8]);// * 0.75f + fcr.FacialFeatures[10] * 0.25f);
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[6]);

            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[66]);
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[68]);
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[69]);
            ProgramCore.Project.DetectedBottomPoints.Add(fcr.FacialFeatures[67]);

            ProgramCore.Project.DetectedTopPoints.Add(fcr.FacialFeatures[66]);
            ProgramCore.Project.DetectedTopPoints.Add(fcr.FacialFeatures[67]);



            ProgramCore.Project.RotatedAngle = fcr.RotatedAngle;

            var aabb = ProgramCore.MainForm.ctrlRenderControl.InitializeShapedotsHelper(true);         // инициализация точек головы. эта инфа тоже сохранится в проект
                                                                                                       //     ProgramCore.MainForm.ctrlRenderControl.ImportPoints();
            ProgramCore.MainForm.UpdateProjectControls(true, aabb);

            //  ProgramCore.Project.ToStream();
            // ProgramCore.MainForm.ctrlRenderControl.UpdateMeshProportions();

            if (ProgramCore.Project.ManType == ManType.Custom)
            {
                ProgramCore.MainForm.ctrlRenderControl.Mode = Mode.SetCustomControlPoints;
                ProgramCore.MainForm.ctrlRenderControl.InitializeCustomControlSpritesPosition();

                var exampleImgPath = Path.Combine(Application.StartupPath, "Plugin", "ControlBaseDotsExample.jpg");
                using (var ms = new MemoryStream(File.ReadAllBytes(exampleImgPath)))                               // Don't use using!!
                    ProgramCore.MainForm.ctrlTemplateImage.SetTemplateImage((Bitmap)Image.FromStream(ms), false);  // устанавливаем картинку помощь для юзера
            }
        }
        public async Task <ServiceResult> PostFile(string UUID, string type)
        //public ServiceResult PostFile(string UUID, string type)
        {
            var fileResult = new FileEx();

            fileResult.Default = false;
            string pathToImage = "";
            string root        = "";

            string basePath = "/Content/Uploads/" + this.CurrentUser.UUID;

            if (type.EqualsIgnoreCase("user") || type.EqualsIgnoreCase("profile") || type.EqualsIgnoreCase("profilemember"))
            {
                basePath = "/Content/Protected/" + this.CurrentUser.UUID;
            }

            try
            {
                if (this.CurrentUser == null)
                {
                    return(ServiceResponse.Error("You must be logged in to upload."));
                }

                #region non async

                //var httpRequest = HttpContext.Current.Request;
                //if (httpRequest.Files.Count < 1)
                //{
                //    return ServiceResponse.Error("Bad request");
                //}

                //foreach (string file in httpRequest.Files)
                //{
                //    var postedFile = httpRequest.Files[file];
                //    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                //    postedFile.SaveAs(filePath);

                //}

                //return ServiceResponse.OK();

                #endregion non async

                HttpRequestMessage request = this.Request;
                if (!request.Content.IsMimeMultipartContent())
                {
                    return(ServiceResponse.Error("Unsupported media type."));
                }

                root = System.Web.HttpContext.Current.Server.MapPath("~" + basePath);

                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }

                var provider = new MultipartFormDataStreamProvider(root);

                //  foreach (MultipartFileData file in provider.FileData)
                //{
                //    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                //    Trace.WriteLine("Server file path: " + file.LocalFileName);

                //    //AppManager app = new AppManager(Globals.DBConnectionKey, "web", this.GetAuthToken(Request));
                //    //string fileName = file.Headers.ContentDisposition.FileName;

                //    //// Clean the file name..
                //    //foreach (var c in Path.GetInvalidFileNameChars()) { fileName = fileName.Replace(c, ' '); }

                //    //if (string.IsNullOrWhiteSpace(fileName))
                //    //    continue;

                //    //fileName = fileName.ToUpper();

                //}
                //return ServiceResponse.OK();

                ServiceResult res = await request.Content.ReadAsMultipartAsync(provider).
                                    ContinueWith <ServiceResult>(o =>
                {
                    if (o.IsFaulted || o.IsCanceled)
                    {
                        _logger.InsertError("o.IsFaulted:" + o.IsFaulted, "AttributesController", "PostFile");
                        _logger.InsertError("o.IsCanceled:" + o.IsCanceled, "AttributesController", "PostFile");
                        _logger.InsertError("o.Exception:" + JsonConvert.SerializeObject(o), "AttributesController", "PostFile");

                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }
                    string fileName   = "";
                    List <string> kvp = o.Result.Contents.First().Headers.First(w => w.Key == "Content-Disposition").Value.ToList()[0].Split(';').ToList();
                    foreach (string value in kvp)
                    {
                        if (value.Trim().StartsWith("filename"))
                        {
                            String[] tmp = value.Split('=');
                            fileName     = DateTime.UtcNow.ToString("yyyyMMdd_hhmmss") + tmp[1].Trim().Replace("\"", "");
                        }

                        if (value.Contains("defaultImage"))        //value.Trim().StartsWith("name"))
                        {
                            fileResult.Default = true;
                        }
                    }
                    // this is the file name on the server where the file was saved
                    string file             = provider.FileData.First().LocalFileName;
                    string originalFilename = Path.GetFileName(file);
                    string destFile         = file.Replace(originalFilename, fileName);
                    try
                    {
                        if (File.Exists(destFile))
                        {
                            File.Delete(destFile);
                        }
                    }
                    catch
                    {     //file may still be locked so don't worry about it.
                    }

                    try
                    {
                        string extension = Path.GetExtension(destFile)?.ToUpper();
                        if (!string.IsNullOrWhiteSpace(extension))
                        {
                            extension = extension.Replace(".", "");
                        }

                        var image = System.Drawing.Image.FromFile(file);
                        using (var resized = ImageEx.ResizeImage(image, 640, 640))
                        {
                            switch (extension)
                            {
                            case "PNG":
                                resized.Save(destFile, ImageFormat.Png);
                                break;

                            case "GIF":
                                resized.Save(destFile, ImageFormat.Gif);
                                break;

                            case "JPEG":
                            case "JPG":
                                resized.Save(destFile, ImageFormat.Jpeg);
                                break;

                            default:
                                ImageEx.SaveJpeg(destFile, resized, 90);
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.Assert(false, ex.Message);
                    }

                    //try
                    //{
                    //    File.Move(file, destFile);
                    //}
                    //catch { }//ditto from above catch

                    file = destFile;

                    string thumbFile = ImageEx.CreateThumbnailImage(file, 64);
                    string ImageUrl  = fileName;
                    string fullUrl   = this.Request.RequestUri.Scheme + "://" + this.Request.RequestUri.Authority + basePath + "/"; // "/Content/Uploads/" + this.CurrentUser.UUID + "/";
                    pathToImage      = fullUrl + thumbFile;                                                                         // ImageUrl;

                    if (fileResult.Default)
                    {
                        this.UpdateImageURL(UUID, type, pathToImage);    //Now update the database.
                    }
                    else
                    {
                        //add other images to attributes

                        AttributeManager atm = new AttributeManager(Globals.DBConnectionKey, this.GetAuthToken(Request));

                        var attribute = new TMG.Attribute()
                        {
                            ReferenceUUID = UUID,
                            ReferenceType = type,
                            Value         = thumbFile,
                            Image         = thumbFile,
                            ValueType     = "ImagePath",
                            Name          = fileResult.Name,
                            AccountUUID   = this.CurrentUser.AccountUUID,
                            DateCreated   = DateTime.UtcNow,
                            CreatedBy     = CurrentUser.UUID,
                            RoleOperation = ">=",
                            RoleWeight    = RoleFlags.MemberRoleWeights.Member,
                            Private       = false,
                            NSFW          = -1
                        };
                        atm.Insert(attribute);
                    }

                    fileResult.UUID       = UUID;
                    fileResult.UUIDType   = type;
                    fileResult.Status     = "saved";
                    fileResult.Image      = fullUrl + ImageUrl;
                    fileResult.ImageThumb = fullUrl + ImageEx.GetThumbFileName(destFile);     //todo check this
                    fileResult.Name       = fileName;

                    return(ServiceResponse.OK(fileName + " uploaded.", fileResult));
                }
                                                                 );

                return(res);
            }
            catch (Exception ex)
            {
                _logger.InsertError("root folder:" + root, "AttributesController", "PostFile");
                _logger.InsertError(ex.DeserializeException(false), "AttributesController", "PostFile");
                return(ServiceResponse.Error("Upload failed."));
            }
        }
Beispiel #4
0
        private static void CropImage(Image sourceImage, string imageName, bool needCrop = true, int angleCount = 0)
        {
            FSDK.TPoint[] pointFeature;

            var image = new FSDK.CImage(new Bitmap(sourceImage));



            var faceRectangle = Rectangle.Empty;

            var facePosition = image.DetectFace();

            if (0 == facePosition.w)
            {
                SaveToFTP(sourceImage, imageName);
                return;
            }

            pointFeature = image.DetectFacialFeaturesInRegion(ref facePosition);

            var left = facePosition.xc - (int)(facePosition.w * 0.6f);

            left = left < 0 ? 0 : left;
            //   int top = facePosition.yc - (int)(facePosition.w * 0.5f);             // верхушку определяет неправильлно. поэтому просто не будем обрезать :)
            var BottomFace = new Vector2(pointFeature[11].x, pointFeature[11].y);

            var distance = pointFeature[2].y - pointFeature[11].y;
            var top      = pointFeature[16].y + distance - 15; // определение высоты по алгоритму старикана

            top = top < 0 ? 0 : top;

            var newWidth = (int)(facePosition.w * 1.2);

            newWidth = newWidth > image.Width || newWidth == 0 ? image.Width : newWidth;

            faceRectangle = new Rectangle(left, top, newWidth,
                                          BottomFace.Y + 15 < image.Height ? (int)(BottomFace.Y + 15) - top : image.Height - top - 1);

            if (needCrop)
            {
                sourceImage = ImageEx.Crop(new Bitmap(sourceImage), faceRectangle);
            }


            // по новой картинке еще раз распознаемм все
            image        = new FSDK.CImage(new Bitmap(sourceImage));
            facePosition = image.DetectFace();
            if (0 == facePosition.w)
            {
                SaveToFTP(sourceImage, imageName);
                return;
            }

            pointFeature = image.DetectFacialFeaturesInRegion(ref facePosition);


            var LeftEyeCenter  = new Vector2(pointFeature[0].x, pointFeature[0].y);
            var RightEyeCenter = new Vector2(pointFeature[1].x, pointFeature[1].y);

            #region Поворот фотки по глазам!



            var v = new Vector2(LeftEyeCenter.X - RightEyeCenter.X, LeftEyeCenter.Y - RightEyeCenter.Y);
            v.Normalize(); // ПД !
            var xVector = new Vector2(1, 0);

            var xDiff = xVector.X - v.X;
            var yDiff = xVector.Y - v.Y;
            var angle = Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI;

            if (Math.Abs(angle) > 1 && angleCount <= 5) // поворачиваем наклоненные головы
            {
                ++angleCount;
                sourceImage = ImageEx.RotateImage(new Bitmap(sourceImage), (float)-angle);
                CropImage(sourceImage, imageName, false, angleCount);
                return;
            }

            #endregion

            #region Корректируем размер фотки

            const int selectedSize = 1024;              // вызывается уже при создании проекта
            var       max          = (float)Math.Max(sourceImage.Width, sourceImage.Height);
            if (max != selectedSize)
            {
                var k = selectedSize / max;
                sourceImage = ImageEx.ResizeImage(sourceImage, new Size((int)Math.Round(sourceImage.Width * k), (int)Math.Round((sourceImage.Height * k))));
            }

            #endregion

            SaveToFTP(sourceImage, imageName);
        }