예제 #1
0
        /// <summary>
        /// функция наложения водяного знака
        /// </summary>
        /// <param name="resultImage">Объект типа ResultImage</param>
        /// <param name="imgLogo"></param>
        /// <returns></returns>
        public static Bitmap CreateWatermark(ResultImage resultImage, Image imgLogo)
        {
            int right  = (int)((double)resultImage.Bmp.Width * 0.03);
            int bottom = (int)((double)resultImage.Bmp.Height * 0.03);

            int dX = resultImage.ImgRightSideShift - (imgLogo.Width + right);
            int dY = resultImage.ImgBottomSideShift - (imgLogo.Height + bottom);

            using (Graphics g = Graphics.FromImage(resultImage.Bmp))
            {
                g.DrawImage(imgLogo, dX, dY, imgLogo.Width, imgLogo.Height);
            }


            return(resultImage.Bmp);
        }
예제 #2
0
        /// <summary>
        /// функция размещения изображения в рамках контейнера
        /// </summary>
        /// <param name="sourceImage"></param>
        /// <param name="action"></param>
        /// <param name="imgBackground"></param>
        /// <param name="containerWidth"></param>
        /// <param name="containerHeight"></param>
        /// <returns></returns>
        public static ResultImage CreateImageInContainer(Image sourceImage, ImageSizeChangeType action, Image imgBackground = null, int containerWidth = DEFAULT_CONTAINER_WIDTH, int containerHeight = DEFAULT_CONTAINER_HEIGHT)
        {
            int newWidth  = sourceImage.Width;
            int newHeight = sourceImage.Height;

            double relX = (double)newWidth / (double)containerWidth;
            double relY = (double)newHeight / (double)containerHeight;

            int dX = 0;
            int dY = 0;

            // предварительно уменьшаем изображение по наименьшей составляющей (ширина или высота) под контейнер,
            // чтобы было легче с ним работать
            //sourceImage = ResizeImage(sourceImage, containerWidth, containerHeight);

            switch (action)
            {
            case ImageSizeChangeType.Inclose:
                if ((relX >= relY) && (relX > 1.0))
                {
                    newWidth  = containerWidth;
                    newHeight = (relX > relY) ? (int)((double)newHeight / relX) : containerHeight;
                }
                else if ((relY > relX) && (relY > 1.0))
                {
                    newHeight = containerHeight;
                    newWidth  = (int)((double)newWidth / relY);
                }

                dX = (int)((double)(containerWidth - newWidth) / 2.0);
                dY = (int)((double)(containerHeight - newHeight) / 2.0);
                break;

            case ImageSizeChangeType.Crop:
                if ((relX >= relY) && (relY > 1.0))
                {
                    newHeight = containerHeight;
                    newWidth  = (relX > relY) ? (int)((double)newWidth / relY) : containerWidth;
                }
                else if ((relY > relX) && (relX > 1.0))
                {
                    newWidth  = containerWidth;
                    newHeight = (int)((double)newHeight / relX);
                }

                dX = (int)((double)(containerWidth - newWidth) / 2.0);
                dY = (int)((double)(containerHeight - newHeight) / 2.0);

                if ((dX < 0) || (dY < 0))
                {
                    int dX1 = 0;
                    int dY1 = 0;

                    if (dX < 0)
                    {
                        dX1 = dX * (-1);
                        dX  = 0;
                    }

                    if (dY < 0)
                    {
                        dY1 = dY * (-1);
                        dY  = 0;
                    }

                    newWidth  = newWidth - (dX1 * 2);
                    newHeight = newHeight - (dY1 * 2);

                    Bitmap bmpSourceImage = new Bitmap(sourceImage);

                    Rectangle section = new Rectangle(dX1, dY1, newWidth, newHeight);

                    sourceImage = bmpSourceImage.Clone(section, bmpSourceImage.PixelFormat);

                    bmpSourceImage.Dispose();
                }

                break;
            }

            ResultImage resultImage = new ResultImage
            {
                Bmp = new Bitmap(containerWidth, containerHeight)
            };


            using (Graphics g = Graphics.FromImage(resultImage.Bmp))
            {
                // здесь при определённых условиях делаем фон контейнера
                // если изображение занимает всю область контейнера, то фон соответственно не нужен
                if ((newWidth < containerWidth) || (newHeight < containerHeight))
                {
                    g.Clear(GetDominantColor(new Bitmap(ResizeImage(sourceImage, ImageResizeMode.OnMinSide, (int)((double)newWidth / 3.0), (int)((double)newHeight / 3.0))))); // заливка фона контейнера
                    // здесь накладываем на фон контейнера фоновый рисунок при условии,
                    // что размеры контейнера совпадают с размерами фонового изображения
                    if ((imgBackground != null) && (containerWidth == imgBackground.Width) && (containerHeight == imgBackground.Height))
                    {
                        g.DrawImage(imgBackground, 0, 0, imgBackground.Width, imgBackground.Height);
                    }
                }

                g.DrawImage(sourceImage, dX, dY, newWidth, newHeight);
            }

            sourceImage.Dispose();

            resultImage.ImgRightSideShift  = (newWidth == containerWidth) ? containerWidth : newWidth + dX;
            resultImage.ImgBottomSideShift = (newHeight == containerHeight) ? containerHeight : newHeight + dY;

            return(resultImage);
        }
예제 #3
0
        public ImgJson SaveImages(HttpFileCollectionBase files, string uniqueImgFolderName, string categFolderName, ImgJson addToList = null, List <ImgSizeSetting> imgSizeList = null)
        {
            if (!CheckFilesExists(files))
            {
                return new ImgJson
                       {
                           CountHistory     = 0,
                           ImgJsonOrderList = new List <ImgJsonOrder>()
                       }
            }
            ;

            #region ImgSizeList
            imgSizeList = imgSizeList ?? new List <ImgSizeSetting> {
                GetImgSizeSetting(FULL_FILE_NAME_PREFIX),           // 1024x720 - full изображение с огрничением 1024x720
                GetImgSizeSetting(MIDDLE_FILE_NAME_PREFIX),         // 400x300 - для карточки объявления
                GetImgSizeSetting(SMALL_FILE_NAME_PREFIX),          // 200x150 - для горячих
                GetImgSizeSetting(SUPER_SMALL_FILE_NAME_PREFIX)     // 60x45 - для превью в карточке
            };
            #endregion

            var imgJson = addToList ?? new ImgJson {
                CountHistory = 0, ImgJsonOrderList = new List <ImgJsonOrder>()
            };
            var folderCategPath = CheckFolderAndCreate(Path.Combine(AdImagesFolder, categFolderName), true);
            var userFolderPath  = CheckFolderAndCreate(Path.Combine(AdImagesFolder, folderCategPath, uniqueImgFolderName), true);

            var imgLogo       = Image.FromFile(LogoPath);       // получаем файл логотипа
            var imgBackground = Image.FromFile(BackgroundPath); // получаем файл фонового изображения

            int maxWidth  = imgSizeList.Max(x => x.Width);      // Максимальный размер в настройках
            int maxHeight = imgSizeList.Max(x => x.Height);     // Минимальный размер в настройках


            ResultImage resultImage = new ResultImage();

            int indexName = 0;

            for (int i = 0; i < files.Count; i++)
            {
                Image resizedImg = null;

                try
                {
                    using (var fullImg = Image.FromStream(files[i].InputStream, useEmbeddedColorManagement: true, validateImageData: false))
                    {
                        resizedImg = ImgManager.ResizeImage(fullImg, ImageResizeMode.OnMinSide, maxWidth, maxHeight);
                    }
                }
                catch
                {
                    resizedImg?.Dispose();
                    files[i].InputStream?.Dispose();
                    continue;
                }


                files[i].InputStream?.Dispose();


                foreach (var e in imgSizeList)
                {
                    // предварительно уменьшаем изображение
                    resultImage.Bmp = (e.Width == maxWidth) && (e.Height == maxHeight)
                                        ? new Bitmap(ImgManager.ResizeImage(resizedImg, ImageResizeMode.OnMaxSide, e.Width, e.Height))
                                        : new Bitmap(ImgManager.ResizeImage(resizedImg, ImageResizeMode.OnMinSide, e.Width, e.Height));
                    resultImage.ImgRightSideShift  = resultImage.Bmp.Width;
                    resultImage.ImgBottomSideShift = resultImage.Bmp.Height;

                    #region proccessing
                    if (e.Width >= DEFAULT_CONTAINER_WIDTH)
                    {
                        int newLogoWidth;

                        if (e.Width == DEFAULT_CONTAINER_WIDTH)
                        {
                            // получаем изображение, вписанное в контейнер
                            resultImage  = ImgManager.CreateImageInContainer(resultImage.Bmp, ImageSizeChangeType.Inclose, imgBackground, e.Width, e.Height);
                            newLogoWidth = (int)((double)e.Width * 0.2);
                        }
                        else
                        {
                            newLogoWidth = (resultImage.Bmp.Width < resultImage.Bmp.Height)
                                         ? (int)((double)resultImage.Bmp.Height * 0.2)
                                         : (int)((double)resultImage.Bmp.Width * 0.2);
                        }


                        Image imgLogoWatermark = imgLogo;
                        if (imgLogo.Width > newLogoWidth)
                        {
                            double relation      = (double)imgLogo.Width / newLogoWidth;
                            int    newLogoHeight = (int)((double)imgLogo.Height / relation);
                            imgLogoWatermark = ImgManager.ResizeLogoImage(imgLogo, new Size(newLogoWidth, newLogoHeight));
                        }

                        resultImage.Bmp = ImgManager.CreateWatermark(resultImage, imgLogoWatermark);
                    }
                    else
                    {
                        resultImage = ImgManager.CreateImageInContainer(resultImage.Bmp, ImageSizeChangeType.Crop, null, e.Width, e.Height);
                    }
                    #endregion


                    //Получаем последний индекс в названии файла
                    indexName = imgJson.CreateIndexName(i);
                    //Путь и имя файла, что там сохранить его
                    var path = Path.Combine(userFolderPath, $"{indexName}-{e.Width}x{e.Height}.jpg");


                    resultImage.Bmp.Save(path, ImageFormat.Jpeg);
                    resultImage.Bmp.Dispose();
                }

                resizedImg.Dispose();

                imgJson.ImgJsonOrderList.Add(new ImgJsonOrder {
                    Order = indexName, IndexName = indexName
                });
            }

            imgLogo.Dispose();
            imgBackground.Dispose();


            imgJson.CountHistory = imgJson.GetMaxIndexNameInList();

            return(imgJson);
        }