private void GetSourceImageInfo()
 {
     if (!isExisted)
     {
         return;
     }
     Database.Entities.Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(sourceImageShortPath) &&
                                                              img.ShortPath.Equals(sourceImageShortPath, StringComparison.Ordinal));
     if (image != null)
     {
         sourceImageWidth  = (int)image.Width;
         sourceImageHeight = (int)image.Height;
     }
     if (!sourceImageWidth.HasValue && !sourceImageHeight.HasValue)
     {
         using (Image <Rgba32> sourceImage = Image.Load(sourceImageFullPath))
         {
             sourceImageWidth  = sourceImage.Width;
             sourceImageHeight = sourceImage.Height;
             addImageInfoToDB  = true;
         }
     }
 }
Exemple #2
0
        public void ApplySettings()
        {
            if (!isExisted)
            {
                return;
            }
            string createdImageFullName = sourceImageName;

            if (widthSetting.HasValue && heightSetting.HasValue)
            {
                createdImageFullName += $"_{widthSetting.Value}x{heightSetting.Value}";
            }
            if (qualitySetting.HasValue)
            {
                createdImageFullName += $"_q{qualitySetting.Value}";
            }
            createdImageFullName += sourceImageExtension;
            CreatedImageFullPath  = pathToImageFolder + createdImageFullName;
            if (!File.Exists(CreatedImageFullPath))
            {
                using (Image <Rgba32> sourceImage = Image.Load(sourceImageFullPath))
                {
                    if (widthSetting.HasValue && heightSetting.HasValue)
                    {
                        sourceImage.Mutate(x => x.Resize(widthSetting.Value, heightSetting.Value));
                    }
                    if (qualitySetting.HasValue)
                    {
                        IImageEncoder imageEncoder = null;
                        switch (sourceImageExtension.ToLower())
                        {
                        case ".jpg":
                        case ".jpeg":
                            var jpegEncoder = new JpegEncoder();
                            jpegEncoder.Quality = qualitySetting.Value;
                            imageEncoder        = jpegEncoder;
                            break;
                            // Настройки сжатия для png
                        }
                        sourceImage.Save(CreatedImageFullPath, imageEncoder);
                    }
                    else
                    {
                        sourceImage.Save(CreatedImageFullPath);
                    }
                }
            }
            CreatedImageSrc = CreatedImageFullPath.Substring(env.GetStorageFolderFullPath().Length - 1);
            if (addImageInfoToDB)
            {
                Database.Entities.Image image = new Database.Entities.Image
                {
                    ShortPath     = sourceImageShortPath,
                    ShortPathHash = OtherFunctions.GetHashFromString(sourceImageShortPath),
                    FullName      = sourceImageShortPath.Substring(sourceImageShortPath.LastIndexOf('/') + 1),
                    Height        = (uint)sourceImageHeight.Value,
                    Width         = (uint)sourceImageWidth.Value
                };
                db.Images.Add(image);
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateException) { }
            }
        }
        public static void UploadProductImageToServer(CMSDatabase db, IFormFile file, int?itemID, HttpContext context, out bool successfullyUploaded)
        {
            successfullyUploaded = true;
            if (!itemID.HasValue || file == null)
            {
                successfullyUploaded = false;
                return;
            }
            ProductPage product = db.ProductPages.AsNoTracking().FirstOrDefault(pp => pp.ID == itemID);

            if (product == null)
            {
                successfullyUploaded = false;
                return;
            }
            IHostingEnvironment env = context.RequestServices.GetRequiredService <IHostingEnvironment>();
            string imagesPath       = $"{env.GetProductsImagesFolderFullPath()}{product.ID}/";

            Directory.CreateDirectory(imagesPath);
            string fullImageName = FileManagerManagementFunctions.GetUniqueFileOrFolderName(imagesPath, product.Alias, ".jpg");
            string pathToFile    = $"{imagesPath}{fullImageName}";

            using (Stream stream = file.OpenReadStream())
            {
                try
                {
                    using (Image <Rgba32> source = SixLabors.ImageSharp.Image.Load(stream))
                    {
                        // Если остались зависимости от предыдущего изображения, то удаляем их
                        DeleteDependentImages(imagesPath, fullImageName);
                        // Добавляем или изменяем информацию в БД
                        string shortPathToImage       = pathToFile.Substring(env.GetStorageFolderFullPath().Length).Insert(0, "/");
                        Database.Entities.Image image = db.Images.FirstOrDefault(img => img.ShortPathHash == OtherFunctions.GetHashFromString(shortPathToImage) &&
                                                                                 img.ShortPath.Equals(shortPathToImage, StringComparison.Ordinal));
                        if (image == null)
                        {
                            image = new Database.Entities.Image
                            {
                                ShortPath     = shortPathToImage,
                                ShortPathHash = OtherFunctions.GetHashFromString(shortPathToImage),
                                FullName      = shortPathToImage.Substring(shortPathToImage.LastIndexOf('/') + 1),
                                Width         = (uint)source.Width,
                                Height        = (uint)source.Height
                            };
                            db.Images.Add(image);
                        }
                        else // Если вдруг каким-то образом информация об изображении не была удалена из БД
                        {
                            image.Width  = (uint)source.Width;
                            image.Height = (uint)source.Height;
                        }
                        db.SaveChanges();
                        source.Save(pathToFile);
                        LogManagementFunctions.AddAdminPanelLog(
                            db: db,
                            context: context,
                            info: $"{product.PageName} (ID-{product.ID.ToString()}): {(context.Items["LogLocalization"] as IAdminPanelLogLocalization)?.ProductImageUploaded}"
                            );
                    }
                }
                catch (NotSupportedException) { successfullyUploaded = false; }
            }
        }