Ejemplo n.º 1
0
        protected byte[] ApplyResize(byte[] pictureBinary, int targetSize, Size originalSize = default(Size))
        {
            var resizeLayer = default(ResizeLayer);

            if (originalSize != default(Size))
            {
                resizeLayer = new ResizeLayer(CalculateDimensions(originalSize, targetSize), ResizeMode.Max);
            }
            else
            {
                //ValidatePicture() only
                resizeLayer = new ResizeLayer(new Size(targetSize, targetSize), ResizeMode.Max);
            }

            using (MemoryStream inStream = new MemoryStream(pictureBinary))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (ImageFactory imageFactory = new ImageFactory())
                    {
                        imageFactory.Load(inStream)
                        .Resize(resizeLayer)
                        .Quality(_mediaSettings.DefaultImageQuality)
                        .Save(outStream);
                        inStream.Dispose();
                        imageFactory.Dispose();
                        return(outStream.ToArray());
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public void RenderBattleMap(Battle b)
        {
            byte[] Battlemap = File.ReadAllBytes(Path.Combine(Directory.GetCurrentDirectory(), "data", "battlemap.png"));

            using (MemoryStream inStream = new MemoryStream(Battlemap))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        imageFactory.Load(inStream);

                        for (int i = 0; i < 9; i++)
                        {
                            for (int j = 0; j < Math.Min(5, b.Battlemap[i].Count); j++)
                            {
                                imageFactory.Overlay(new ImageLayer()
                                {
                                    Image    = PrepareToken(b.Battlemap[i][j].Token),
                                    Opacity  = 100,
                                    Position = GetPoint(i, j)
                                });
                            }
                        }
                        imageFactory.Format(new PngFormat {
                            Quality = 100
                        });
                        imageFactory.Save(Path.Combine(Directory.GetCurrentDirectory(), "data", "temp", "battlemap-" + b.ChannelId + ".png"));
                        imageFactory.Dispose();
                    }
                }
            }
        }
        public IEnumerable <Blob> UploadImage(string container, string key, ImageUpload imageUpload)
        {
            List <Blob> blobs = new List <Blob>();

            try
            {
                string[] base64 = imageUpload.Content.Split(new char[] { ',' });
                var      image  = Convert.FromBase64String(base64[1]);

                var blobContainer = GetContainer(container);

                ISupportedImageFormat compressionFormat = new JpegFormat {
                    Quality = imageUpload.Config.CompressionQuality
                };

                foreach (var size in imageUpload.Config.Sizes)
                {
                    using (MemoryStream outStream = new MemoryStream())
                    {
                        ImageFactory imageFactory = null;
                        try
                        {
                            imageFactory = new ImageFactory();

                            imageFactory = imageFactory.Load(image)
                                           .Resize(new System.Drawing.Size(size.Width, size.Height));

                            if (imageUpload.Config.EnableCompression)
                            {
                                imageFactory = imageFactory.Format(compressionFormat);
                            }

                            imageFactory.Save(outStream);

                            var blob = blobContainer.GetBlockBlobReference($"{key}_{Guid.NewGuid().ToString()}_{size.Key}.{imageFactory.CurrentImageFormat.DefaultExtension}");
                            blob.UploadFromStream(outStream);

                            blobs.Add(new Blob(key, size.Key, blob.Uri.OriginalString));
                        }
                        finally
                        {
                            if (imageFactory != null)
                            {
                                imageFactory.Dispose();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Failed to upload image container: {0}, key: {2}", container, key);
                throw ex;
            }

            return(blobs);
        }
Ejemplo n.º 4
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (SourceImage != null)
         {
             SourceImage.Dispose();
         }
     }
 }
Ejemplo n.º 5
0
        public List <byte[]> ProcessData(List <byte[]> input)
        {
            int imageQty = BitConverter.ToInt32(input[0], 0),
                opacity  = 100 / imageQty;

            //Work out required size of the final image
            Size largestSize = new Size(0, 0);

            for (var i = 1; i < input.Count; i++)
            {
                using (MemoryStream inStream = new MemoryStream(input[i]))
                {   //only use the size to save on memory
                    Size imageSize = Image.FromStream(inStream).Size;

                    if (imageSize.Width > largestSize.Width)
                    {
                        largestSize.Width = imageSize.Width;
                    }
                    if (imageSize.Height > largestSize.Height)
                    {
                        largestSize.Height = imageSize.Height;
                    }
                }
            }

            ImageFactory image = new ImageFactory();

            image.Format(new JpegFormat());
            image.Quality(100);
            image.Load(new Bitmap(largestSize.Width, largestSize.Height));

            for (var i = 1; i < input.Count; i++)
            {
                ImageLayer layer = new ImageLayer {
                    Opacity = opacity
                };
                using (MemoryStream inStream = new MemoryStream(input[i]))
                    layer.Image = Image.FromStream(inStream);
                layer.Size = layer.Image.Size;

                image.Overlay(layer);
            }

            using (MemoryStream outStream = new MemoryStream())
            {
                image.Save(outStream);
                image.Dispose();

                List <byte[]> output = new List <byte[]>();
                output.Add(outStream.ToArray());
                return(output);
            }
        }
Ejemplo n.º 6
0
        void Scale()
        {
            var SelectedFolder = Directory.GetFiles(PathToLoadFolder);
            int NumberOfFiles  = SelectedFolder.Length;
            int NameCounter    = 1;

            foreach (var Item in SelectedFolder)
            {
                ImageFactory imageFactory = new ImageFactory();
                imageFactory.Load(Item);
                imageFactory.Resize(ScaleSize);
                imageFactory.Save($@"{PathForImages}\{NameCounter}.jpg");
                imageFactory.Dispose();
                NameCounter++;
            }
        }
Ejemplo n.º 7
0
    public static string ProcessScreenshot(string filePath)
    {
        Console.WriteLine("Processing " + Path.GetFileName(filePath) + "...");
        var       imgBytes      = File.ReadAllBytes(filePath);
        CropLayer fifaCrop      = new CropLayer(11.5f, 34.8f, 32.5f, 17.5f, CropMode.Percentage);
        CropLayer tempCrop      = new CropLayer(0, 0, 0, 92f, CropMode.Percentage);
        Image     originalImage = Image.FromFile(filePath);
        string    savePath      = (Path.GetDirectoryName(filePath) + @"\Processed\" + Path.GetFileName(filePath));

        using (var tempStream1 = new MemoryStream())
            using (var tempStream2 = new MemoryStream())
                using (var imageFactory = new ImageFactory(false))
                {
                    imageFactory.Load(originalImage)
                    .Saturation(-100)
                    .Crop(fifaCrop)
                    .Contrast(100)
                    .Save(tempStream1)
                    .Crop(tempCrop)
                    .Filter(MatrixFilters.Invert)
                    .Save(tempStream2);

                    Image      goalsImage = Image.FromStream(tempStream2);
                    ImageLayer goals      = new ImageLayer()
                    {
                        Image    = goalsImage,
                        Size     = goalsImage.Size,
                        Opacity  = 100,
                        Position = new Point(originalImage.Size.Height)
                    };

                    imageFactory.Load(tempStream1)
                    .Overlay(goals)
                    .Save(savePath);

                    tempStream1.Dispose();
                    tempStream2.Dispose();
                    imageFactory.Dispose();
                }
        Console.WriteLine("Image processed and saved to " + savePath);
        return(savePath);
    }
Ejemplo n.º 8
0
        private void GenerateCardView(List <CatalogCode> codes)
        {
            ImageFactory output = new ImageFactory().Load(new Bitmap(1, 1));

            foreach (CatalogCode code in codes)
            {
                string     path = CardPath(code);
                ImageLayer temp = new ImageLayer();
                temp.Image    = Image.FromFile(path);
                temp.Position = new Point(0, output.Image.Height);
                ResizeLayer rl = new ResizeLayer(new Size(Math.Max(temp.Image.Width, output.Image.Width),
                                                          output.Image.Height + temp.Image.Height), ResizeMode.BoxPad, AnchorPosition.TopLeft);
                output.Resize(rl);
                output.Overlay(temp);
                temp.Dispose();
            }

            output.Image.Save(folder + tempFolder + tempFile, ImageFormat.Tiff);
            output.Dispose();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a cropped version of the image at the size specified in the parameters
        /// </summary>
        /// <param name="originalFilePath">The full path of the original file</param>
        /// <param name="newFilePath">The full path of the new file</param>
        /// <param name="width">The new image width</param>
        /// <param name="height">The new image height</param>
        /// <returns>A bool to show if the method was successful or not</returns>
        private bool CreateCroppedImage(string originalFilePath, string newFilePath, int width, int height)
        {
            bool         success      = false;
            ImageFactory imageFactory = new ImageFactory();

            try
            {
                imageFactory.Load(originalFilePath);
                ResizeLayer layer = new ResizeLayer(new System.Drawing.Size(width, height), ResizeMode.Crop, AnchorPosition.Center);
                imageFactory.Resize(layer);
                imageFactory.AutoRotate();
                imageFactory.Save(newFilePath);
                success = true;
            }
            catch (System.Exception)
            {
                success = false;
            }
            finally
            {
                imageFactory.Dispose();
            }
            return(success);
        }
Ejemplo n.º 10
0
 public void Reset()
 {
     Image?.Dispose(); Image         = null;
     tumbImage?.Dispose(); tumbImage = null;
 }
Ejemplo n.º 11
0
        protected byte[] ApplyWatermark(byte[] pictureBinary)
        {
            //no Watermark Text and Watermark Overlay? Return
            if (string.IsNullOrEmpty(_mediaSettings.WatermarkText) &&
                string.IsNullOrEmpty(_mediaSettings.WatermarkOverlayID) &&
                _mediaSettings.WatermarkOverlayID == "0")
            {
                return(pictureBinary);
            }

            //UX this piece of code needs to be here, otherwise "Input stream is not a supported format" Exception
            var pictureWidth  = default(int);
            var pictureHeight = default(int);

            using (MemoryStream pictureStream = new MemoryStream(pictureBinary))
            {
                Bitmap bitmap = new Bitmap(Image.FromStream(pictureStream));
                pictureWidth  = bitmap.Size.Width;
                pictureHeight = bitmap.Size.Height;
                pictureStream.Dispose();
            }

            using (MemoryStream inStream = new MemoryStream(pictureBinary))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (ImageFactory imageFactory = new ImageFactory())
                    {
                        imageFactory
                        .Load(inStream);

                        if (!string.IsNullOrEmpty(_mediaSettings.WatermarkText))
                        {
                            var calculatedHorizontalPixel = (pictureWidth * _mediaSettings.WatermarkPositionXPercent) / 100;
                            var calculatedVerticalPixel   = (pictureHeight * _mediaSettings.WatermarkPositionYPercent) / 100;
                            var calculatedFontSize        = (pictureHeight * _mediaSettings.WatermarkFontSizePercent) / 100;

                            imageFactory
                            .Watermark(new TextLayer()
                            {
                                Text        = _mediaSettings.WatermarkText,
                                Style       = _mediaSettings.WatermarkStyle,
                                FontColor   = _mediaSettings.WatermarkFontColor,
                                FontFamily  = new FontFamily(_mediaSettings.WatermarkFontFamily),
                                Opacity     = _mediaSettings.WatermarkOpacityPercent,
                                DropShadow  = _mediaSettings.WatermarkDropShadow,
                                Vertical    = _mediaSettings.WatermarkVertical,
                                Position    = new Point(calculatedHorizontalPixel, calculatedVerticalPixel),
                                RightToLeft = _mediaSettings.WatermarkRightToLeft,
                                FontSize    = calculatedFontSize <= 0 ? 1 : calculatedFontSize
                            });
                        }

                        if (!(string.IsNullOrEmpty(_mediaSettings.WatermarkOverlayID) || _mediaSettings.WatermarkOverlayID == "0"))
                        {
                            var overlayWidth  = default(int);
                            var overlayHeight = default(int);
                            //picture is a horizontal rectangle, so Overlay will be tailored in context of shorter dimension - Vertical Height
                            if (pictureWidth > pictureHeight)
                            {
                                overlayWidth  = (pictureHeight * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                                overlayHeight = (pictureHeight * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                            }
                            //picture is a vertical rectangle, so Overlay will be tailored in context of shorter dimension - Horizontal Width
                            else if (pictureWidth < pictureHeight)
                            {
                                overlayWidth  = (pictureWidth * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                                overlayHeight = (pictureWidth * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                            }
                            //picture is a square
                            else if (pictureWidth == pictureHeight)
                            {
                                overlayWidth  = (pictureWidth * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                                overlayHeight = (pictureHeight * _mediaSettings.WatermarkOverlaySizePercent) / 100;
                            }

                            //calculate X and Y center of Picture
                            var overlayHalfWidth  = overlayWidth / 2;
                            var overlayHalfHeight = overlayHeight / 2;

                            //calculate the absolute X and Y pixel of Picture bitmap
                            //where Overlay should be located
                            var pictureHorizontalPixel = (pictureWidth * _mediaSettings.WatermarkOverlayPositionXPercent) / 100;
                            var pictureVerticalPixel   = (pictureHeight * _mediaSettings.WatermarkOverlayPositionYPercent) / 100;

                            //calculate the absolute X and Y pixel of Picture bitmap
                            //where Center of Overlay should be located
                            var overlayHorizontalPosition = pictureHorizontalPixel - overlayHalfWidth;
                            var overlayVerticalPosition   = pictureVerticalPixel - overlayHalfHeight;

                            //prevent to get beyond top or left edge of Picture
                            //(happens when WatermarkOverlaySizePercent is set to low value)
                            if (overlayHorizontalPosition < 0)
                            {
                                overlayHorizontalPosition = 0;
                            }
                            if (overlayVerticalPosition < 0)
                            {
                                overlayVerticalPosition = 0;
                            }

                            var overlayByteArray = LoadPictureBinary(new Picture()
                            {
                                Id = _mediaSettings.WatermarkOverlayID
                            });
                            using (var overlayStream = new MemoryStream(overlayByteArray))
                            {
                                imageFactory
                                .Overlay(new ImageLayer()
                                {
                                    Image    = Image.FromStream(overlayStream),
                                    Opacity  = _mediaSettings.WatermarkOverlayOpacityPercent,
                                    Position = new Point(overlayHorizontalPosition, overlayVerticalPosition),
                                    Size     = new Size(overlayWidth, overlayHeight)
                                });
                                overlayStream.Dispose();
                            }
                        }

                        imageFactory
                        .Save(outStream);

                        inStream.Dispose();
                        imageFactory.Dispose();
                        return(outStream.ToArray());
                    }
                }
            }
        }
Ejemplo n.º 12
0
 public void Dispose()
 {
     ImageFactory.Dispose();
 }
Ejemplo n.º 13
0
 public void Dispose()
 {
     _imageFactory?.Dispose();
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Cleans resources.
 /// </summary>
 public void Dispose()
 {
     _editor?.Dispose();
     _startImage?.Dispose();
     _tempImage?.Dispose();
 }
        private void PrintDatesButton_Click(object sender, EventArgs e)
        {
            ChooseFolderButton.Enabled = false;
            PrintDatesButton.Enabled   = false;

            FileStream fs    = null;
            Image      image = null;

            byte[]       source;
            ImageFactory imageFactory = new ImageFactory();
            Regex        r = new Regex(":");
            int          dated = 0, notDated = 0;

            string[] picturesPaths = Directory.GetFiles(@path, "*.jpg");

            ProgressBar.Maximum = picturesPaths.Length;
            ProgressBar.Step    = 1;

            foreach (string p in picturesPaths)
            {
                try // case property is unset or error with reading/saving image
                {
                    // preparing image
                    fs     = new FileStream(p, FileMode.Open, FileAccess.Read);
                    image  = Image.FromStream(fs, false, false);
                    source = File.ReadAllBytes(p);
                    MemoryStream imageStream = new MemoryStream(source);

                    // reading neccesary properties
                    PropertyItem propertyDate   = image.GetPropertyItem(0x9003);
                    PropertyItem propertyWidth  = image.GetPropertyItem(0x0100);
                    PropertyItem propertyHeight = image.GetPropertyItem(0x0101);
                    int          height         = BitConverter.ToInt32(propertyHeight.Value, 0);

                    PropertyItem[] allProperties = image.PropertyItems;

                    // preparing date
                    DateTime date    = DateTime.Parse(r.Replace(Encoding.UTF8.GetString(propertyDate.Value), "-", 2));
                    string   dateStr = ConvertDate(date);

                    // preparing position
                    Point position = new Point(
                        (int)(BitConverter.ToInt32(propertyWidth.Value, 0) * .85),
                        (int)(height * .95)
                        );

                    // preparing font size
                    int fontSize = (int)(height * .03);

                    // unlocking path to the image and deleting old one
                    fs.Close();
                    File.Delete(p);

                    // printing date
                    imageFactory.Load(imageStream)
                    .Watermark(new ImageProcessor.Imaging.TextLayer()
                    {
                        Position = position,

                        Text      = dateStr,
                        Style     = FontStyle.Bold,
                        FontColor = Color.White,
                        Opacity   = 80,
                        FontSize  = fontSize,
                    })
                    .Save(imageStream);
                    Console.WriteLine("date: " + dateStr);

                    dated++;

                    // retrieving image propeties
                    image = Image.FromStream(imageStream, false, false);
                    foreach (PropertyItem property in allProperties)
                    {
                        image.SetPropertyItem(property);
                    }

                    // saving image with date
                    image.Save(p);
                }
                catch
                {
                    notDated++;
                    Console.WriteLine("Error: probably image does\'t have one of properties");
                }
                finally
                {
                    // clering memory
                    fs.Dispose();
                    image.Dispose();
                    imageFactory.Dispose();

                    GC.Collect();
                }


                ProgressBar.PerformStep();
            }

            // show confirmation
            string            title   = rm.GetString("confirmation_title");
            string            message = rm.GetString("confirmation_text_1") + dated + rm.GetString("confirmation_text_2") + notDated;
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            DialogResult      result  = MessageBox.Show(message, title, buttons);

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                Reset();
            }
        }
Ejemplo n.º 16
0
        public string ConvertWebp(string ruta, float maxHeight, float maxWidth)
        {
            Image image  = Image.FromFile(ruta);
            var   height = (float)(image.Height);
            var   width  = (float)(image.Width);

            float prop = 0;

            //Se calculan los valores proporcionales al maximo ancho y alto requerido
            if (height > width)
            {
                prop   = CalcularProporcionH(height, width);
                height = maxHeight;
                width  = maxHeight / prop;
            }
            else if (width > height)
            {
                prop   = CalcularProporcionW(height, width);
                width  = maxWidth;
                height = maxWidth / prop;
            }
            else if (height == width)
            {
                height = maxHeight;
                width  = maxWidth;
            }
            image.Dispose();


            //Leo la imagen en arreglo matricial de una ruta especifica
            byte[] imageBytes = File.ReadAllBytes(ruta);
            // Format is automatically detected though can be changed.
            //ISupportedImageFormat format = new PngFormat { Quality = 70 };
            ISupportedImageFormat format = new JpegFormat {
                Quality = 70
            };

            Size size = new Size((int)width, (int)height);

            using (MemoryStream inStream = new MemoryStream(imageBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // Inicializa ImageFactory sobrecargando EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        // Carga, redimensiona, formatea y lo pone en la salida
                        imageFactory.Load(inStream)
                        //.Resize(size)
                        .Format(format)
                        .Save(outStream);
                        //Guarda la imagen en formato webp
                        //imageFactory.Save(@"E:\Img\PruebaRefactory.webp");
                        var    baseImage          = (byte[])(new ImageConverter()).ConvertTo(imageFactory.Image, typeof(byte[]));
                        string base64encodedImage = System.Convert.ToBase64String(baseImage);
                        imageFactory.Dispose();
                        return(base64encodedImage);
                    }
                }
            }
        }
Ejemplo n.º 17
0
 //public enum ImageFormat
 //{
 //    WebP,
 //    jpeg,
 //    png,
 //    tiff
 //}
 public void Dispose()
 {
     factory?.Dispose();
 }