Ejemplo n.º 1
0
        //protected static readonly object trimmingLockObject = new System.Object();
        public byte[] ПолучитьФайлПросмотр(object id_file, ImageType type, int width, int height, ImageFormat format, long Качество, КонструкторИзображения Конструктор, string domain)
        {
            #region FileName
            var data     = new DataClient();
            var path     = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["ПросмотрХранилище"], domain);
            var filename = null as string;

            switch (format)
            {
            case ImageFormat.Jpg:
            {
                filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}_{5}.jpg",
                                         id_file, width, height,
                                         type.ToString(), Качество,
                                         Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain)));
            }
            break;

            case ImageFormat.Png:
            {
                filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}.png",
                                         id_file, width, height,
                                         type.ToString(),
                                         Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain)));
            }
            break;
            }
            #endregion

            var full_filename = Path.Combine(path, filename);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (System.IO.File.Exists(full_filename))
            {
                return(System.IO.File.ReadAllBytes(full_filename));
            }
            else
            {
                var imgOutput = null as Bitmap;
                var canvas    = null as Graphics;
                try
                {
                    using (var output = new MemoryStream())
                    {
                        try
                        {
                            var image      = null as Bitmap;
                            var filestream = ПолучитьФайлПолностью(id_file, Хранилище.Оперативное, domain);
                            if (filestream != null)
                            {
                                using (var mc = new MemoryStream(filestream))
                                    using (image = new Bitmap(mc))
                                    {
                                        #region очистить фон
                                        if (Конструктор != null && Конструктор.ПрозрачныйФон)
                                        {
                                            var firstPixelColor = image.GetPixel(0, 0);
                                            if (firstPixelColor != null && Color.Transparent.ToArgb() != firstPixelColor.ToArgb())
                                            {
                                                var floodFiller = new UnsafeQueueLinearFloodFiller()
                                                {
                                                    Bitmap    = new PictureBoxScroll.EditableBitmap(image, PixelFormat.Format32bppArgb),
                                                    FillColor = Color.Transparent,
                                                    Tolerance = new byte[] { 5, 5, 5 }
                                                };
                                                floodFiller.FloodFill(new Point(0, 0));

                                                if (floodFiller.Bitmap != null && floodFiller.Bitmap.Bitmap != null)
                                                {
                                                    image.Dispose();
                                                    image = new Bitmap(floodFiller.Bitmap.Bitmap);
                                                }
                                            }
                                        }
                                        #endregion

                                        #region trimming
                                        if (Конструктор != null && Конструктор.ОбрезатьПустоеМесто)
                                        {
                                            // Find the min/max non-white/transparent pixels
                                            var min = new Point(int.MaxValue, int.MaxValue);
                                            var max = new Point(int.MinValue, int.MinValue);


                                            var isAlpha = image.PixelFormat.HasFlag(PixelFormat.Alpha);
                                            for (int x = 0; x < image.Width; ++x)
                                            {
                                                for (int y = 0; y < image.Height; ++y)
                                                {
                                                    var pixelColor = image.GetPixel(x, y);

                                                    if ((pixelColor.R < 245 && pixelColor.G < 245 && pixelColor.B < 245 && pixelColor.A > 0) ||
                                                        (isAlpha && pixelColor.A > 0))
                                                    {
                                                        if (x < min.X)
                                                        {
                                                            min.X = x;
                                                        }
                                                        if (y < min.Y)
                                                        {
                                                            min.Y = y;
                                                        }

                                                        if (x > max.X)
                                                        {
                                                            max.X = x;
                                                        }
                                                        if (y > max.Y)
                                                        {
                                                            max.Y = y;
                                                        }
                                                    }
                                                }
                                            }

                                            var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y);
                                            var newBitmap     = new Bitmap(cropRectangle.Width, cropRectangle.Height);
                                            newBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                                            var g = Graphics.FromImage(newBitmap);
                                            g.DrawImage(image, 0, 0, cropRectangle, GraphicsUnit.Pixel);
                                            g.Flush();

                                            image.Dispose();
                                            image = newBitmap;
                                        }
                                        #endregion

                                        var newSize = new Size(width, height);
                                        switch (type)
                                        {
                                        case ImageType.Full:
                                        {
                                            newSize                   = new Size(width, height);
                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height);
                                            canvas.Flush();
                                        }
                                        break;

                                        case ImageType.Thumbnail:
                                        {
                                            int _width = Math.Min(image.Size.Height, image.Size.Width);
                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, _width, _width), GraphicsUnit.Pixel);
                                            canvas.Flush();
                                        }
                                        break;

                                        case ImageType.Resize:
                                        {
                                            if (newSize.Width > 0 && newSize.Height == 0)                // Сжатие по ширине (принудительное)
                                            {
                                                newSize.Height = (int)(((double)newSize.Width / (double)image.Size.Width) * image.Size.Height);
                                            }
                                            else if (newSize.Width == 0 && newSize.Height > 0)          // Сжатие по высоте (принудительное)
                                            {
                                                newSize.Width = (int)(((double)newSize.Height / (double)image.Size.Height) * image.Size.Width);
                                            }
                                            else
                                            {
                                                int sourceWidth  = image.Size.Width;
                                                int sourceHeight = image.Size.Height;

                                                float nPercent  = 0;
                                                float nPercentW = 0;
                                                float nPercentH = 0;

                                                nPercentW = ((float)newSize.Width / (float)sourceWidth);
                                                nPercentH = ((float)newSize.Height / (float)sourceHeight);

                                                if (nPercentH < nPercentW)
                                                {
                                                    nPercent = nPercentH;
                                                }
                                                else
                                                {
                                                    nPercent = nPercentW;
                                                }

                                                newSize = new Size((int)(sourceWidth * nPercent), (int)(sourceHeight * nPercent));
                                            }

                                            imgOutput                 = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
                                            canvas                    = Graphics.FromImage(imgOutput);
                                            canvas.SmoothingMode      = SmoothingMode.Default;
                                            canvas.CompositingQuality = CompositingQuality.HighQuality;
                                            canvas.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                            if (format == ImageFormat.Jpg)
                                            {
                                                canvas.Clear(Color.White);
                                            }
                                            canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height);
                                            canvas.Flush();
                                        }
                                        break;
                                        }

                                        #region Добавить слои из конструктора
                                        if (Конструктор != null && Конструктор.Слои != null && canvas != null)
                                        {
                                            foreach (var item in Конструктор.Слои)
                                            {
                                                if (item.id_file == null || item.id_file.Equals(0m))
                                                {
                                                    continue;
                                                }

                                                using (var mcLayer = new MemoryStream(ПолучитьФайлПолностью(item.id_file, Хранилище.Оперативное, domain)))
                                                    using (var imageLayer = new Bitmap(mcLayer))
                                                    {
                                                        canvas.DrawImage(imageLayer, item.x, item.y,
                                                                         Convert.ToInt32(imageLayer.Width * (item.width > 0 ? item.width : 1.0)),
                                                                         Convert.ToInt32(imageLayer.Height * (item.height > 0 ? item.height : 1.0)));
                                                    }
                                            }
                                        }
                                        #endregion
                                    }
                            }
                            else
                            {
                                imgOutput = new Bitmap(width, height);
                                canvas    = Graphics.FromImage(imgOutput);
                                canvas.Clear(Color.White);
                                canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1);
                                canvas.DrawString(
                                    "Not Found " + data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain),
                                    new Font("Tahoma", 8),
                                    Brushes.Gray,
                                    new RectangleF(0, 0, width, height),
                                    new StringFormat()
                                {
                                    Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            imgOutput = new Bitmap(width, height);
                            canvas    = Graphics.FromImage(imgOutput);
                            canvas.Clear(Color.White);
                            canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1);
                            canvas.DrawString(
                                data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain),
                                new Font("Tahoma", 8),
                                Brushes.Gray,
                                new RectangleF(0, 0, width, height),
                                new StringFormat()
                            {
                                Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
                            });

                            ConfigurationClient.WindowsLog("FileService", string.Empty, domain, ex.ToString());
                        }

                        #region Вывод
                        switch (format)
                        {
                        case ImageFormat.Jpg:
                        {
                            var ep = new EncoderParameters(1);
                            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Качество);
                            ImageCodecInfo imageCodecInfo = null;
                            foreach (ImageCodecInfo item in ImageCodecInfo.GetImageEncoders())
                            {
                                if (item.MimeType == "image/jpeg")
                                {
                                    imageCodecInfo = item;
                                    break;
                                }
                            }
                            imgOutput.Save(output, imageCodecInfo, ep);
                        }
                        break;

                        case ImageFormat.Png:
                        {
                            imgOutput.Save(output, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        break;
                        }

                        //сохранить файл
                        System.IO.File.WriteAllBytes(full_filename, output.ToArray());
                        #endregion

                        return(output.ToArray());
                    }
                }
                finally
                {
                    if (canvas != null)
                    {
                        canvas.Dispose();
                    }
                    if (imgOutput != null)
                    {
                        imgOutput.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public byte[] ПолучитьФайлПросмотрПоНазванию(object id_node, string ИмяФайла, ImageType type, int width, int height, ImageFormat format, long Качество, КонструкторИзображения Конструктор, Хранилище хранилище, string domain)
        {
            //var query = new Query();
            //query.КоличествоВыводимыхДанных = 1;
            //query.КоличествоВыводимыхСтраниц = 1;
            //query.Типы.Add("Файл%");
            //query.УсловияПоиска.Add(new Query.УсловиеПоиска() { Атрибут = "ИдентификаторОбъекта", Значение = ИмяФайла });
            //query.ДобавитьВыводимыеКолонки(new string[] { "ИдентификаторОбъекта" });
            //query.МестаПоиска.Add(new Query.МестоПоиска() { id_node = id_node, МаксимальнаяГлубина = 1 });
            //var file = new DataClient().Поиск(query, хранилище, domain).AsEnumerable().SingleOrDefault();

            var file = new DataClient()._СписокФайлов(id_node, хранилище, domain).FirstOrDefault(p => p.ИдентификаторФайла == ИмяФайла);

            if (file == null)
            {
                return(null);
            }
            return(ПолучитьФайлПросмотр(file.id_node, type, width, height, format, Качество, Конструктор, domain));
        }
Ejemplo n.º 3
0
 public byte[] ПолучитьФайлПросмотр(object id_file, ImageType type, int width, int height, ImageFormat format, long Качество, КонструкторИзображения Конструктор)
 {
     return(ПолучитьФайлПросмотр(id_file, type, width, height, ImageFormat.Jpg, 70L, Конструктор, Client.Domain));
 }