Ejemplo n.º 1
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();
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public byte[] GetImageByteArray(string fileName, ISupportedImageFormat imageFormat)
        {
            try
            {
                byte[] imgBytes;
                _imageFactory.Load(fileName);
                if (!Equals(_imageFactory.CurrentImageFormat, imageFormat))
                {
                    _imageFactory.Format(imageFormat);
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    _imageFactory.Save(ms);
                    ms.Flush();
                    imgBytes = ms.ToArray();
                }

                return(imgBytes);
            }
            catch (Exception exception)
            {
                Log.Error(exception, $"GetImageByteArray Failed using filename: {fileName} and image format: {imageFormat}");
                return(null);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Processes the loaded image. Inheritors should NOT save the image, this is done by the main method.
        /// </summary>
        /// <param name="query">Query</param>
        /// <param name="processor">Processor instance</param>
        protected virtual void ProcessImageCore(ProcessImageQuery query, ImageFactory processor)
        {
            // Resize
            var size = query.MaxWidth != null || query.MaxHeight != null
                                ? new Size(query.MaxWidth ?? 0, query.MaxHeight ?? 0)
                                : Size.Empty;

            if (!size.IsEmpty)
            {
                processor.Resize(new ResizeLayer(
                                     size,
                                     resizeMode: ConvertScaleMode(query.ScaleMode),
                                     anchorPosition: ConvertAnchorPosition(query.AnchorPosition),
                                     upscale: false));
            }

            if (query.BackgroundColor.HasValue())
            {
                processor.BackgroundColor(ColorTranslator.FromHtml(query.BackgroundColor));
            }

            // Format
            if (query.Format != null)
            {
                var format = query.Format as ISupportedImageFormat;

                if (format == null && query.Format is string)
                {
                    var requestedFormat = ((string)query.Format).ToLowerInvariant();
                    switch (requestedFormat)
                    {
                    case "jpg":
                    case "jpeg":
                        format = new JpegFormat();
                        break;

                    case "png":
                        format = new PngFormat();
                        break;

                    case "gif":
                        format = new GifFormat();
                        break;
                    }
                }

                if (format != null)
                {
                    processor.Format(format);
                }
            }

            // Set Quality
            if (query.Quality.HasValue)
            {
                processor.Quality(query.Quality.Value);
            }
        }
        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.º 5
0
        public IImageTransformer Format(IImageFormat format)
        {
            if (format is IPImageFormat ipFormat)
            {
                _image.Format(ipFormat.WrappedFormat);
                return(this);
            }

            throw new ArgumentException("Passed image type must be '{0}'.".FormatCurrent(typeof(IPImageFormat)), nameof(format));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Performs the Format effect from the ImageProcessor library.
        /// </summary>
        /// <param name="image">The image with which to apply the effect.</param>
        /// <param name="format">The ISupportedImageFormat that the Image will be converted to upon saving.</param>
        /// <returns>A new image that will be saved with the corresponding ImageFormat.</returns>
        public Image Format(Image image, ISupportedImageFormat format)
        {
            using var factory = new ImageFactory();

            factory.Load(image);
            factory.Format(format);

            var result = factory.Image;

            return(new Bitmap(result));
        }
Ejemplo n.º 7
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.º 8
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            try
            {
                ISupportedImageFormat format = this.DynamicParameter;
                factory.Format(format);
            }
            catch (Exception ex)
            {
                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return factory.Image;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            try
            {
                ISupportedImageFormat format = this.DynamicParameter;
                factory.Format(format);
            }
            catch (Exception ex)
            {
                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(factory.Image);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            string      format    = this.DynamicParameter;
            bool        isIndexed = false;
            ImageFormat imageFormat;

            switch (format)
            {
            case "png":
                imageFormat = ImageFormat.Png;
                break;

            case "png8":
                imageFormat = ImageFormat.Png;
                isIndexed   = true;
                break;

            case "bmp":
                imageFormat = ImageFormat.Bmp;
                break;

            case "gif":
                imageFormat = ImageFormat.Gif;
                isIndexed   = true;
                break;

            case "tif":
            case "tiff":
                imageFormat = ImageFormat.Tiff;
                break;

            case "ico":
                imageFormat = ImageFormat.Icon;
                break;

            default:
                // Should be a jpeg or jpg.
                imageFormat = ImageFormat.Jpeg;
                break;
            }

            // Set the internal property.
            factory.OriginalExtension = string.Format(".{0}", format);
            factory.Format(imageFormat, isIndexed);

            return(factory.Image);
        }
Ejemplo n.º 11
0
        private async Task OnFileUpload(MessageContext <FileUploadEvent> messageContext, EventHandlerFunc <FileUploadEvent> next)
        {
            var stream        = messageContext.Message.Stream;
            var imageSettings = messageContext.ComponentResolver.Resolve <IImageSettings>();

            using (var imageFactory = new ImageFactory())
            {
                try
                {
                    imageFactory.Load(stream);
                    stream.Dispose();
                    stream = new MemoryStream();
                    messageContext.Message.Stream = stream;
                }
                catch (ImageFormatException)
                {
                    // This is not an image or the format is not supported.
                    await next(messageContext);

                    return;
                }

                var rectangle = CalculateRectangle(imageFactory.Image, _watermarkImage, _position);

                new PngFormat().ApplyProcessor(new Blit
                {
                    DynamicParameter = new ImageLayer
                    {
                        Image    = _watermarkImage,
                        Opacity  = _opacity,
                        Size     = rectangle.Size,
                        Position = rectangle.Location
                    }
                }.ProcessImage, imageFactory);

                var format = ImageFormats.GetFormatForFile(messageContext.Message.File);
                format.Quality = imageSettings.Quality;
                imageFactory.Format(format);

                imageFactory.Save(stream);
                stream.Position = 0;
            }

            await next(messageContext);
        }
        public MemoryStream ProcessAvatar(byte[] image)
        {
            using (var inStream = new MemoryStream(image))
            {
                var outStream = new MemoryStream();
                using (var imageFactory = new ImageFactory(true, true))
                {
                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(inStream);
                    imageFactory.Format(new JpegFormat());
                    imageFactory.Quality(ApplicationConstants.AvatarSmallQualityPercentage);
                    imageFactory.Resize(new ResizeLayer(new Size(ApplicationConstants.AvatarSmallW, ApplicationConstants.AvatarSmallH)));
                    imageFactory.Save(outStream);

                    return(outStream);
                }
            }
        }
Ejemplo n.º 13
0
        //converting graphic files, the names of which are specified in the FileNames array into the ResultDirectory directory.
        public static bool ConvertPhotos(ItemCollection FileNames, string ResultDirectory, IProgress <int> progress)
        {
            System.Drawing.Size MainPic, StandartPic, SmallPic;
            ImageProcessor.Imaging.Formats.ISupportedImageFormat newformat;

            StandartPic = new System.Drawing.Size(PicsConfig.StandartPicWidth, PicsConfig.StandartPicHeight);
            MainPic     = new System.Drawing.Size(PicsConfig.MainPicWidth, PicsConfig.MainPicHeight);
            SmallPic    = new System.Drawing.Size(PicsConfig.SmallPicWidth, PicsConfig.SmallPicHeight);
            newformat   = new ImageProcessor.Imaging.Formats.JpegFormat();

            using (ImageFactory Image_Factory = new ImageFactory(preserveExifData: true))
            {
                for (int Index = 0; Index < FileNames.Count; ++Index)
                {
                    Image_Factory.Load(FileNames[Index].ToString());
                    Image_Factory.Resize(StandartPic);
                    Image_Factory.BackgroundColor(System.Drawing.Color.White);
                    Image_Factory.Format(newformat);
                    Image_Factory.Quality(100);
                    Image_Factory.Save(ResultDirectory + "\\" + (Index + 1).ToString("D4") + ".jpg");

                    if (Index == 0)
                    {
                        Image_Factory.Resize(MainPic);
                        Image_Factory.BackgroundColor(System.Drawing.Color.White);
                        Image_Factory.Save(ResultDirectory + "\\" + (Index + 1).ToString("D4") + "_f.jpg");
                    }

                    Image_Factory.Resize(SmallPic);
                    Image_Factory.BackgroundColor(System.Drawing.Color.White);
                    Image_Factory.Save(ResultDirectory + "\\" + (Index + 1).ToString("D4") + "_sm.jpg");

                    progress.Report(Index + 1);
                }
            }

            MessageBox.Show("Image conversion is completed", "Information!", MessageBoxButton.OK, MessageBoxImage.Information);
            return(true);
        }
Ejemplo n.º 14
0
        private async Task OnFileUpload(MessageContext <FileUploadEvent> messageContext, EventHandlerFunc <FileUploadEvent> next)
        {
            var stream        = messageContext.Message.Stream;
            var imageSettings = messageContext.ComponentResolver.Resolve <IImageSettings>();

            var originalPosition = stream.Position;

            using (var imageFactory = new ImageFactory())
            {
                try
                {
                    imageFactory.Load(stream);
                    stream.Position = originalPosition;
                }
                catch (ImageFormatException)
                {
                    // This is not an image or the format is not supported.
                    await next(messageContext);

                    return;
                }

                imageFactory.Overlay(new ImageLayer
                {
                    Image = _watermarkImage, Opacity = 50, Size = imageFactory.Image.Size
                });

                var format = ImageFormats.GetFormatForFile(messageContext.Message.File);
                format.Quality = imageSettings.Quality;

                imageFactory.Format(format);
                imageFactory.Save(stream);
            }

            await next(messageContext);
        }
Ejemplo n.º 15
0
 public void ChangeFormat(ISupportedImageFormat format)
 {
     convertingFactory.Format(format);
 }
Ejemplo n.º 16
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;
            _http    = _client.GetService <HttpService>();

            manager.CreateCommands("image", group =>
            {
                group.CreateCommand("caption")
                .Parameter("uri", ParameterType.Required)
                .Parameter("parameters", ParameterType.Unparsed)
                .Description("Adds text to an Image.\n<`uri`> ⦗`color`⦘ ⦗`alpha`⦘ ⦗`position`⦘ ⦗`fontsize`⦘ ⦗`dropshadow`⦘\nExample usage:\n⦗`cap http://myimage.png red 0.5 center arial 12 1 hello world`⦘\n⦗`cap http://myimage.png hello world`⦘")
                .Alias("cap")
                .Do(async e =>
                {
                    if (e.Args.Any())
                    {
                        var args   = getArgs(e);
                        string uri = e.Args[0];

                        if (args.Any())
                        {
                            if (await isImage(uri))
                            {
                                string file = "img_cap_tmp" + Guid.NewGuid().ToString() + await getImageExtension(uri);

                                try
                                {
                                    await DownloadImage(uri, file);
                                }
                                catch (WebException ex)
                                {
                                    await _client.ReplyError(e, ex.Message);
                                    _client.Log.Error("captions", ex);

                                    if (File.Exists(file))
                                    {
                                        File.Delete(file);
                                    }
                                    return;
                                }

                                if (File.Exists(file))
                                {
                                    byte[] pb = File.ReadAllBytes(file);

                                    var asd        = new TextLayer();
                                    asd.Text       = args?["text"];
                                    asd.FontColor  = args.ContainsKey("color") ? System.Drawing.Color.FromName(args["color"]) : System.Drawing.Color.White;
                                    asd.FontFamily = args.ContainsKey("font") ? FontFamily.Families.Where(x => x.Name == args["font"]).FirstOrDefault() : FontFamily.GenericSerif;
                                    asd.DropShadow = args.ContainsKey("dropshadow") ? bool.Parse(args["dropshadow"]) : false;
                                    // asd.Position = Point.Empty;
                                    asd.Opacity  = args.ContainsKey("opacity") ? int.Parse(args["opacity"]) : 100;
                                    asd.Style    = args.ContainsKey("style") ? (FontStyle)Enum.Parse(typeof(FontStyle), args["style"], true) : FontStyle.Regular;
                                    asd.FontSize = args.ContainsKey("size") ? int.Parse(args["size"]) : 20;

                                    ISupportedImageFormat format = new PngFormat {
                                        Quality = 100
                                    };

                                    using (MemoryStream ins = new MemoryStream(pb))
                                        using (MemoryStream outs = new MemoryStream())
                                            using (ImageFactory iff = new ImageFactory(true))
                                            {
                                                iff.Load(ins)
                                                .Watermark(asd)
                                                .Format(format)
                                                .Save(outs);
                                                await e.Channel.SendFile("output.png", outs);
                                            }
                                    File.Delete(file);
                                }
                                else
                                {
                                    await _client.ReplyError(e, "Couldn't find your image on my end. Bug @Techbot about it.");
                                    return;
                                }
                            }
                            else
                            {
                                await _client.ReplyError(e, "That doesn't seem to be an image...");
                            }
                        }
                        else
                        {
                            await _client.ReplyError(e, "No Parameters provided, aborting...");
                            return;
                        }
                    }
                    else
                    {
                        await _client.Reply(e, "Usage: `cap [link] <text>`");
                    }
                });
                group.CreateCommand("edit")
                .Parameter("uri", ParameterType.Required)
                .Parameter("parameters", ParameterType.Unparsed)
                .Description("transforms an image.\nSupported Parameters:\n\n\nTint: `tint=red`\nCensor: `censor=x;y;w;h`\n`Scaling: `w=num or h=num`\n`blur=num`\n`rot=num`\n`filp=true/false`\n`crop=true + (top=num or bottom=num or left=num or right=num)`")
                .Alias("e")
                .Do(async e =>
                {
                    if (e.Args.Any())
                    {
                        var args   = getArgs(e);
                        string uri = e.Args[0];

                        if (await isImage(uri))
                        {
                            string file = "img_e_tmp" + Guid.NewGuid().ToString() + await getImageExtension(uri);
                            try
                            {
                                await DownloadImage(uri, file);
                            }
                            catch (WebException ex)
                            {
                                await _client.ReplyError(e, ex.Message);
                                _client.Log.Error("captions", ex);

                                if (File.Exists(file))
                                {
                                    File.Delete(file);
                                }
                                return;
                            }
                            if (File.Exists(file))
                            {
                                byte[] pb = File.ReadAllBytes(file);

                                ISupportedImageFormat format = new PngFormat {
                                    Quality = 100
                                };

                                using (MemoryStream ins = new MemoryStream(pb))
                                    using (MemoryStream outs = new MemoryStream())
                                        using (ImageFactory iff = new ImageFactory(true))
                                        {
                                            iff.Load(ins);
                                            if (args.ContainsKey("rot"))
                                            {
                                                iff.Rotate(int.Parse(args["rot"]));
                                            }
                                            if (args.ContainsKey("flip"))
                                            {
                                                iff.Flip(bool.Parse(args["flip"]));
                                            }
                                            if (args.ContainsKey("blur"))
                                            {
                                                iff.GaussianBlur(int.Parse(args["blur"]));
                                            }
                                            if (args.ContainsKey("ecrop"))
                                            {
                                                iff.EntropyCrop(byte.Parse(args["ecrop"]));
                                            }
                                            if (args.ContainsKey("pixelate"))
                                            {
                                                iff.Pixelate(int.Parse(args["pixelate"]));
                                            }
                                            if (args.ContainsKey("tint"))
                                            {
                                                iff.Tint(System.Drawing.Color.FromName(args["tint"]));
                                            }
                                            if (args.ContainsKey("replacecolor"))
                                            {
                                                string[] rcargs          = args["replacecolor"].Split(';');
                                                System.Drawing.Color tar = System.Drawing.Color.FromName(rcargs[0]);
                                                System.Drawing.Color rep = System.Drawing.Color.FromName(rcargs[1]);

                                                if (rcargs.Length > 2 && int.Parse(rcargs[2]) >= 128 || int.Parse(rcargs[2]) < 0)
                                                {
                                                    await _client.ReplyError(e, "Fuzzines mix and max values are 0 - 128");
                                                    File.Delete(file);
                                                    return;
                                                }
                                                int fuzz = rcargs.Length > 2 ? int.Parse(rcargs[2]) : 128;

                                                iff.ReplaceColor(tar, rep, fuzz);
                                            }
                                            if (args.ContainsKey("censor"))
                                            {
                                                string[] cargs = args["censor"].Split(';');
                                                var pixels     = int.Parse(cargs[4]);
                                                var x          = int.Parse(cargs[0]);
                                                var y          = -int.Parse(cargs[1]);
                                                var w          = int.Parse(cargs[2]);
                                                var h          = int.Parse(cargs[3]);

                                                iff.Pixelate(pixels, new Rectangle(new Point(x, y), new Size(w, h)));
                                            }
                                            if (args.ContainsKey("w") || args.ContainsKey("h"))
                                            {
                                                int width = 0, height = 0;

                                                if (args.ContainsKey("w"))
                                                {
                                                    width = int.Parse(args["w"]);
                                                }

                                                if (args.ContainsKey("h"))
                                                {
                                                    height = int.Parse(args["h"]);
                                                }
                                                iff.Resize(new ResizeLayer(new Size(width, height), ResizeMode.Stretch, AnchorPosition.Center, true, null, new Size(5000, 5000)));
                                            }
                                            if (args.ContainsKey("crop"))
                                            {
                                                int top = 0, bottom = 0, left = 0, right = 0;

                                                // is there a better way to do this?

                                                if (args.ContainsKey("top"))
                                                {
                                                    top = int.Parse(args["top"]);
                                                }
                                                if (args.ContainsKey("bottom"))
                                                {
                                                    bottom = int.Parse(args["bottom"]);
                                                }
                                                if (args.ContainsKey("left"))
                                                {
                                                    left = int.Parse(args["left"]);
                                                }
                                                if (args.ContainsKey("right"))
                                                {
                                                    right = int.Parse(args["right"]);
                                                }

                                                iff.Crop(new CropLayer(
                                                             top,
                                                             bottom,
                                                             left,
                                                             right,
                                                             CropMode.Percentage));
                                            }

                                            iff
                                            .Format(format)
                                            .Save(outs);
                                            await e.Channel.SendFile("output.png", outs);
                                        }
                                File.Delete(file);
                            }
                            else
                            {
                                await _client.ReplyError(e, "Couldn't find your image on my end. Bug @Techbot about it.");
                                return;
                            }
                        }
                        else
                        {
                            await _client.ReplyError(e, "That doesn't seem to be an image...");
                        }
                    }
                });
            });
        }
Ejemplo n.º 17
0
 public void Export(string path, ISupportedImageFormat format)
 {
     _mainImageFactory.Format(format)
     .Save(path);
 }
Ejemplo n.º 18
0
        private async Task <List <Stream> > GetCollectionPages(ICommandContext ctxt)
        {
            List <Stream> returnstream = new List <Stream>();

            byte[]       bgBytes     = File.ReadAllBytes(@"..\..\img\pepe\collection_bg.png");
            byte[]       overBytes   = File.ReadAllBytes(@"..\..\img\pepe\collection_overlay.png");
            byte[]       frameBytes  = File.ReadAllBytes(@"..\..\img\pepe\card_frame.png");
            MemoryStream frameStream = new MemoryStream(frameBytes);

            //DataTable dt = await GetCollection(ctxt.User.Id);
            DataTable dt = await GetCollection(ctxt.User.Id);

            if (dt.Rows.Count == 0)
            {
                return(new List <Stream>());
            }

            //card size
            int[] cardSize = new int[] { 182, 259 };
            //image dimensions
            int[] imageDimension = new int[] { 1920, 1080 };

            int maxCards     = 30,
                maxstack     = 3,
                maxPerRow    = 10,
                xPadding     = 4,
                yPadding     = 60,
                yOffset      = 160,
                yStackOffset = 16;

            int prevDataRow = -1;
            int currDataRow = 0;

            int slots = 0;

            foreach (DataRow row in dt.Rows)
            {
                int num = Convert.ToInt32(row["cnt"]) / maxstack;

                if (Convert.ToInt32(row["cnt"]) % maxstack != 0)
                {
                    num++;
                }

                slots += num;
            }

            int pages = slots / maxCards;

            if (slots % maxCards != 0)
            {
                pages++;
            }

            await ReplyAsync("Rendering (this may take up to 30 seconds)....");

            //run this code once per page
            for (int i = 0; i < pages; i++)
            {
                //determine number of cards on page
                int cards = slots > maxCards ? maxCards : slots;

                //determine number of rows
                int numRows = cards / maxPerRow;
                if (cards % maxPerRow != 0)
                {
                    numRows++;
                }

                //determine best distribution of cards e.g. 23 -> [7, 8, 8]
                //23 / 3 = 7
                //7 * 3 = 21
                //23 - 21 = 2
                //remainder of 2, ergo [7, 8, 8]
                //17 / 2 = 8
                //8 * 2 = 16
                //17-16 = 1
                //remainder of 1, ergo [6,7]
                int   evenDiv   = cards / numRows;
                int   product   = evenDiv * numRows;
                int   remainder = cards - product;
                int[] rows      = new int[numRows];
                for (int j = 0; j < numRows; j++)
                {
                    if (remainder == 0)
                    {
                        rows[j] = evenDiv;
                    }
                    else
                    {
                        rows[j] = evenDiv + 1;
                        remainder--;
                    }
                }

                rows = rows.Reverse().ToArray();

                //determine row positions based on cards on page
                Tuple <int, int>[] cardPos = new Tuple <int, int> [cards];
                int totalHeight            = numRows * cardSize[1] + yPadding * (numRows - 1);
                int ySlack = imageDimension[1] - yOffset - totalHeight;
                int yStart = ySlack / 2 + yOffset;


                int counter = 0;
                for (int j = 0; j < numRows; j++)
                {
                    int rowWidth = cardSize[0] * rows[j] + (xPadding * (rows[j] - 1));
                    int xSlack   = imageDimension[0] - rowWidth;
                    int xStart   = xSlack / 2;
                    for (int k = 0; k < rows[j]; k++)
                    {
                        int xPos = xStart + (cardSize[0] + xPadding) * k;
                        int yPos = yStart + (cardSize[1] + yPadding) * j;
                        cardPos[counter] = new Tuple <int, int>(xPos, yPos);
                        counter++;
                    }
                }

                using (MemoryStream bgStream = new MemoryStream(bgBytes))
                {
                    using (MemoryStream overStream = new MemoryStream(overBytes))
                    {
                        using (ImageFactory imageFactory = new ImageFactory())
                        {
                            imageFactory.Format(new PngFormat());

                            MemoryStream      outStream = new MemoryStream();
                            List <ImageLayer> overlays  = new List <ImageLayer>();
                            int currCardPos             = 0;
                            int prevCardPos             = 0;
                            int currStackLvl            = 0;

                            while (currCardPos < cards)
                            {
                                DataRow currCard = dt.Rows[currDataRow];
                                Stream  cs;
                                if (prevDataRow == currDataRow)
                                {
                                    cs = frameStream;
                                }
                                else
                                {
                                    cs = await GetCardImageStreamAsync(currCard["name"].ToString(), currCard["image_extension"].ToString(), Convert.ToInt32(currCard["rarity"]), Convert.ToBoolean(currCard["foil"]));
                                }
                                cs.Position = 0;

                                //resize layer for resizing card
                                ResizeLayer cardResizeLayer = new ResizeLayer(new System.Drawing.Size(cardSize[0], cardSize[1]), ResizeMode.Stretch);

                                //resize card
                                imageFactory.Load(cs)
                                .Resize(cardResizeLayer)
                                .Save(outStream);


                                //overlay layer for overlaying card
                                int y = cardPos[currCardPos].Item2;
                                y -= yStackOffset * currStackLvl;

                                ImageLayer cardImageLayer = new ImageLayer();
                                cardImageLayer.Image    = System.Drawing.Image.FromStream(outStream);
                                cardImageLayer.Position = new System.Drawing.Point(cardPos[currCardPos].Item1, y);
                                overlays.Add(cardImageLayer);

                                dt.Rows[currDataRow]["cnt"] = Convert.ToInt32(dt.Rows[currDataRow]["cnt"]) - 1;

                                if (Convert.ToInt32(dt.Rows[currDataRow]["cnt"]) == 0)
                                {
                                    currDataRow++;

                                    currStackLvl = 0;
                                    currCardPos++;
                                }
                                else
                                {
                                    currStackLvl++;

                                    if (currStackLvl >= maxstack)
                                    {
                                        currStackLvl = 0;
                                        currCardPos++;
                                    }
                                }

                                prevCardPos = currCardPos;

                                if (!cs.Equals(frameStream))
                                {
                                    cs.Dispose();
                                }
                            }

                            imageFactory.Load(bgStream);

                            foreach (ImageLayer layer in overlays)
                            {
                                imageFactory.Overlay(layer);
                            }


                            TextLayer titleTextLayer = new TextLayer();
                            titleTextLayer.Text       = $"{ctxt.User.Username.ToUpper()}'s COLLECTION: PAGE {i + 1} OF {pages}";
                            titleTextLayer.FontFamily = new System.Drawing.FontFamily("Beleren");
                            titleTextLayer.FontSize   = 34;
                            System.Drawing.SizeF titlesize = System.Drawing.Graphics.FromImage(overlays[0].Image).MeasureString(titleTextLayer.Text, new System.Drawing.Font(titleTextLayer.FontFamily, titleTextLayer.FontSize, System.Drawing.GraphicsUnit.Pixel));
                            titleTextLayer.Position  = new System.Drawing.Point(imageDimension[0] / 2 - (int)titlesize.Width / 2, yOffset / 2 - (int)titlesize.Height / 2);
                            titleTextLayer.FontColor = System.Drawing.Color.Black;

                            ImageLayer overImageLayer = new ImageLayer();
                            overImageLayer.Image    = System.Drawing.Image.FromStream(overStream);
                            overImageLayer.Position = new System.Drawing.Point(0, 0);
                            overImageLayer.Opacity  = 40;

                            imageFactory.Overlay(overImageLayer)
                            .Watermark(titleTextLayer)
                            .Save(outStream);
                            returnstream.Add(outStream);
                        }
                    }
                }
                slots -= cards;
            }
            GC.Collect();
            frameStream.Dispose();
            return(returnstream);
        }
Ejemplo n.º 19
0
        private Stream GetCardImageStream(string name, string extension, int rarity, bool foil)
        {
            string filename = CardnameToFilename(name);

            //get pepe
            string path       = @"..\..\img\pepe\",
                   emblemPath = @"..\..\img\pepe\rarity_system\",
                   rarityText = String.Empty;

            MemoryStream cardStream = new MemoryStream();

            switch (rarity)
            {
            case 1:
                path       += @"common\";
                emblemPath += @"pepe_common.png";
                rarityText  = "Frog";
                break;

            case 2:
                path       += @"uncommon\";
                emblemPath += @"pepe_uncommon.png";
                rarityText  = "Dire Frog";
                break;

            case 3:
                path       += @"rare\";
                emblemPath += @"pepe_rare.png";
                rarityText  = "Hate Speech";
                break;

            case 4:
                path       += @"mythic_rare\";
                emblemPath += @"pepe_mythic_rare.png";
                rarityText  = "Legendary Hate Speech";
                break;
            }

            path += filename + extension;

            byte[] pepeBytes = File.ReadAllBytes(path),
            emblemBytes = File.ReadAllBytes(emblemPath),
            logoBytes   = File.ReadAllBytes(@"..\..\img\pepe\rarity_system\pepe.png"),
            frameBytes  = File.ReadAllBytes(@"..\..\img\pepe\card_frame.png"),
            blankBytes  = File.ReadAllBytes(@"..\..\img\pepe\blank_layer.png"),
            foilBytes   = File.ReadAllBytes(@"..\..\img\pepe\foil.png");

            using (MemoryStream blankStream = new MemoryStream(blankBytes))
            {
                using (MemoryStream pepeStream = new MemoryStream(pepeBytes))
                {
                    using (MemoryStream frameStream = new MemoryStream(frameBytes))
                    {
                        using (MemoryStream logoStream = new MemoryStream(logoBytes))
                        {
                            using (MemoryStream emblemStream = new MemoryStream(emblemBytes))
                            {
                                using (ImageFactory imageFactory = new ImageFactory())
                                {
                                    MemoryStream outStream = new MemoryStream();

                                    //resize layer for resizing pepe
                                    ResizeLayer pepeResizeLayer = new ResizeLayer(new System.Drawing.Size(659, 774), ResizeMode.Stretch);

                                    //resize pepe
                                    imageFactory.Load(pepeStream)
                                    .Resize(pepeResizeLayer)
                                    .Save(outStream);

                                    //overlay layer for overlaying pepe
                                    ImageLayer pepeImageLayer = new ImageLayer();
                                    pepeImageLayer.Image    = System.Drawing.Image.FromStream(outStream);
                                    pepeImageLayer.Position = new System.Drawing.Point(38, 111);

                                    //overlay layer for overlaying card frame
                                    ImageLayer frameImageLayer = new ImageLayer();
                                    frameImageLayer.Image = System.Drawing.Image.FromStream(frameStream);

                                    //resize logo
                                    ResizeLayer logoResizeLayer = new ResizeLayer(new System.Drawing.Size(80, 64), ResizeMode.Stretch);
                                    imageFactory.Load(logoStream)
                                    .Resize(logoResizeLayer)
                                    .Save(outStream);

                                    //overlay layer for overlaying logo
                                    ImageLayer logoImageLayer = new ImageLayer();
                                    logoImageLayer.Image    = System.Drawing.Image.FromStream(outStream);
                                    logoImageLayer.Position = new System.Drawing.Point(332, 886);

                                    //resize rarity emblem
                                    ResizeLayer emblemResizeLayer = new ResizeLayer(new System.Drawing.Size(40, 32), ResizeMode.Stretch);
                                    imageFactory.Load(emblemStream)
                                    .Resize(emblemResizeLayer)
                                    .Save(outStream);

                                    //overlay layer for overlaying emblem
                                    ImageLayer emblemImageLayer = new ImageLayer();
                                    emblemImageLayer.Image    = System.Drawing.Image.FromStream(outStream);
                                    emblemImageLayer.Position = new System.Drawing.Point(640, 905);

                                    //calculate width of card name in Beleren font
                                    int fontSize = 42;

                                    System.Drawing.SizeF textsize = System.Drawing.Graphics.FromImage(emblemImageLayer.Image).MeasureString(name, new System.Drawing.Font("Beleren", fontSize, System.Drawing.GraphicsUnit.Pixel));


                                    while (textsize.Width > 644)
                                    {
                                        fontSize--;
                                        textsize = System.Drawing.Graphics.FromImage(emblemImageLayer.Image).MeasureString(name, new System.Drawing.Font("Beleren", fontSize, System.Drawing.GraphicsUnit.Pixel));
                                    }

                                    //text layer for card name
                                    TextLayer nameTextLayer = new TextLayer();
                                    nameTextLayer.Text       = name;
                                    nameTextLayer.FontFamily = new System.Drawing.FontFamily("Beleren");
                                    nameTextLayer.FontSize   = fontSize;
                                    nameTextLayer.Position   = new System.Drawing.Point(46, 49 + 23 - (int)textsize.Height / 2);
                                    nameTextLayer.FontColor  = System.Drawing.Color.Black;

                                    //text layer for rarity text

                                    fontSize = 34;
                                    textsize = System.Drawing.Graphics.FromImage(emblemImageLayer.Image).MeasureString(rarityText, new System.Drawing.Font("Beleren", fontSize, System.Drawing.GraphicsUnit.Pixel));

                                    while (textsize.Width > 260)
                                    {
                                        fontSize--;
                                        textsize = System.Drawing.Graphics.FromImage(emblemImageLayer.Image).MeasureString(rarityText, new System.Drawing.Font("Beleren", fontSize, System.Drawing.GraphicsUnit.Pixel));
                                    }

                                    TextLayer rarityTextLayer = new TextLayer();
                                    rarityTextLayer.Text       = rarityText;
                                    rarityTextLayer.FontFamily = new System.Drawing.FontFamily("Beleren");
                                    rarityTextLayer.FontSize   = fontSize;
                                    rarityTextLayer.Position   = new System.Drawing.Point(51, 894 + 23 - (int)textsize.Height / 2);
                                    rarityTextLayer.FontColor  = System.Drawing.Color.Black;

                                    //text layer for pepe text
                                    System.Drawing.SizeF pepesize      = System.Drawing.Graphics.FromImage(emblemImageLayer.Image).MeasureString("Pepe", new System.Drawing.Font("Beleren", fontSize, System.Drawing.GraphicsUnit.Pixel));
                                    TextLayer            pepeTextLayer = new TextLayer();
                                    pepeTextLayer.Text       = "Pepe";
                                    pepeTextLayer.FontFamily = new System.Drawing.FontFamily("Beleren");
                                    pepeTextLayer.FontSize   = 34;
                                    pepeTextLayer.Position   = new System.Drawing.Point(580 - (int)pepesize.Width, 899);
                                    pepeTextLayer.FontColor  = System.Drawing.Color.Black;

                                    imageFactory.Load(blankStream)
                                    .Overlay(pepeImageLayer)
                                    .Overlay(frameImageLayer)
                                    .Overlay(logoImageLayer)
                                    .Overlay(emblemImageLayer)
                                    .Watermark(nameTextLayer)
                                    .Watermark(rarityTextLayer)
                                    .Watermark(pepeTextLayer);

                                    if (foil)
                                    {
                                        using (MemoryStream foilStream = new MemoryStream(foilBytes))
                                        {
                                            //overlay layer for overlaying foil
                                            ImageLayer foilLayer = new ImageLayer();
                                            foilLayer.Image   = System.Drawing.Image.FromStream(foilStream);
                                            foilLayer.Opacity = 20;

                                            imageFactory.Overlay(foilLayer);
                                        }
                                    }

                                    imageFactory.Format(new PngFormat())
                                    .Save(outStream);
                                    cardStream = outStream;
                                }
                            }
                        }
                    }
                }
            }
            return(cardStream);

            //layers, from foreground to background
            //1. foil, if applicable
            //2. text
            //3. emblem
            //4. card frame
            //5. pepe

            //the pepe must be streched to 659 x 774 and will be placed on the image at (38,111)
            //the text must be sized to fit a box of size 644x46 at (46,44)
            //the emblem will be shrunk to 82x73 at sit at (327,879)
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            string format = this.DynamicParameter;
            bool isIndexed = false;
            ImageFormat imageFormat;
            switch (format)
            {
                case "png":
                    imageFormat = ImageFormat.Png;
                    break;
                case "png8":
                    imageFormat = ImageFormat.Png;
                    isIndexed = true;
                    break;
                case "bmp":
                    imageFormat = ImageFormat.Bmp;
                    break;
                case "gif":
                    imageFormat = ImageFormat.Gif;
                    isIndexed = true;
                    break;
                case "tif":
                case "tiff":
                    imageFormat = ImageFormat.Tiff;
                    break;
                case "ico":
                    imageFormat = ImageFormat.Icon;
                    break;
                default:
                    // Should be a jpeg or jpg.
                    imageFormat = ImageFormat.Jpeg;
                    break;
            }

            // Set the internal property.
            factory.OriginalExtension = string.Format(".{0}", format);
            factory.Format(imageFormat, isIndexed);

            return factory.Image;
        }
        public DataAccessResponseType ProcessApplicationImage(string accountId, string storagePartition, string sourceContainerName, string sourceFileName, int formatWidth, int formatHeight, string folderName, string type, int quality, ImageCropCoordinates imageCropCoordinates, ImageEnhancementInstructions imageEnhancementInstructions)
        {
            //Create image id and response object
            string imageId  = System.Guid.NewGuid().ToString();
            var    response = new DataAccessResponseType();

            //var imageSpecs = Sahara.Core.Settings.Imaging.Images.ApplicationImage;
            //var setSizes = imageSpecs.SetSizes;
            //var folderName = imageSpecs.ParentName;


            //-------------------------------------------------
            // REFACTORING NOTES
            //-------------------------------------------------
            // In this scenario we have ApplicationImages hard coded to 600x300 for the LARGE size. We then create a medium and small dynmically (as well as a thumbnail hardcoded to 96px tall)(specific sizes can be factored in if required).
            // In extended scenarios we can pass these specs from CoreServices to clients via a call or from a Redis Cache or WCF fallback.
            // In scenarios where accounts have "Flexible Schemas" we can retreive these properties from a Redis or WCF call for each account based on that accounts set properties.
            //-----------------------------------------------------------------------------


            //var largeSize = new ApplicationImageSize{X=600, Y=300, Name="Large", NameKey = "large"};
            //var mediumSize = new ApplicationImageSize { X = Convert.ToInt32(largeSize.X / 1.25), Y = Convert.ToInt32(largeSize.Y / 1.25), Name = "Medium", NameKey = "medium" }; //<-- Med is 1/1.25 of large
            //var smallSize = new ApplicationImageSize { X = largeSize.X / 2, Y = largeSize.Y / 2, Name = "Small", NameKey = "small" }; //<-- Small is 1/2 of large

            //We calculate thumbnail width based on a set height of 96px.
            //Must be a Double and include .0 in calculation or will ALWAYS calculate to 0!
            //double calculatedThumbnailWidth = ((96.0 / largeSize.Y) * largeSize.X); //<-- Must be a Double and include .0 or will calculate to 0!

            //var thumbnailSize = new ApplicationImageSize { X = (int)calculatedThumbnailWidth, Y = 96, Name = "Thumbnail", NameKey = "thumbnail" }; //<-- Thumbnail is 96px tall, width is calculated based on this

            //We are going to loop through each size during processing
            //var setSizes = new List<ApplicationImageSize> { largeSize, mediumSize, smallSize, thumbnailSize };

            //Folder name within Blob storage for application image collection
            //var folderName = "applicationimages"; //" + imageId; //<-- Each image lives within a folder named after it's id: /applicationimages/[imageid]/[size].jpg

            //Image Format Settings
            var outputFormatString = "." + type;



            ISupportedImageFormat outputFormatProcessorProperty; // = new JpegFormat { Quality = 90 }; // <-- Format is automatically detected though can be changed.

            //ImageFormat outputFormatSystemrawingFormat; // = System.Drawing.Imaging.ImageFormat.Jpeg;


            if (type == "gif")
            {
                outputFormatProcessorProperty = new GifFormat {
                    Quality = quality
                };                                                                   // <-- Format is automatically detected though can be changed.
                //outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if (type == "png")
            {
                outputFormatProcessorProperty = new PngFormat {
                    Quality = quality
                };                                                                   // <-- Format is automatically detected though can be changed.
                //outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Png;
            }
            else
            {
                outputFormatProcessorProperty = new JpegFormat {
                    Quality = quality
                };                                                                    // <-- Format is automatically detected though can be changed.
                //outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
            }

            /**/

            //TO DO: IF ASPECT RATIO EXISTS THEN WE DETRIMINE THE SET SIZE (1 only) by method



            //Create instance of ApplicationImageDocumentModel to store image details into DocumentDB
            // var applicationImageDocumentModel = new ApplicationImageDocumentModel();
            //applicationImageDocumentModel.Id = imageId;
            // applicationImageDocumentModel.FilePath = folderName; //<--Concatenates with each FileName for fil location

            //Note: We store all images in a single folder to make deletions more performant

            // applicationImageDocumentModel.FileNames = new ApplicationImageFileSizes();


            //Get source file as MemoryStream from Blob storage and apply image processing tasks to each spcification
            using (MemoryStream sourceStream = Common.GetAssetFromIntermediaryStorage(sourceContainerName, sourceFileName))
            {
                //var sourceBmp = new Bitmap(sourceStream); //<--Convert to BMP in order to run verifications

                //Verifiy Image Settings Align With Requirements

                /*
                 * var verifySpecsResponse = Common.VerifyCommonImageSpecifications(sourceBmp, imageSpecs);
                 * if (!verifySpecsResponse.isSuccess)
                 * {
                 *  //return if fails
                 *  return verifySpecsResponse;
                 * }*/


                //Assign properties to the DocumentDB Document representation of this image
                //applicationImageDocumentModel.FileNames.Large = "large" + outputFormatString;
                //applicationImageDocumentModel.FileNames.Medium = "medium" + outputFormatString;
                //applicationImageDocumentModel.FileNames.Small = "small" + outputFormatString;
                //a/pplicationImageDocumentModel.FileNames.Thumbnail = "thumbnail" + outputFormatString;

                //Create 3 sizes (org, _sm & _xs)
                //List<Size> imageSizes = new List<Size>();

                Dictionary <Size, string> imageSizes = new Dictionary <Size, string>();

                imageSizes.Add(new Size(formatWidth, formatHeight), "");            //<-- ORG (no apennded file name)
                imageSizes.Add(new Size(formatWidth / 2, formatHeight / 2), "_sm"); //<-- SM (Half Size)
                imageSizes.Add(new Size(formatWidth / 4, formatHeight / 4), "_xs"); //<-- XS (Quarter Size)

                foreach (KeyValuePair <Size, string> entry in imageSizes)
                {
                    Size   processingSize   = entry.Key;
                    string appendedFileName = entry.Value;

                    #region Image Processor & Storage

                    //Final location for EACH image will be: http://[uri]/[containerName]/[imageId]_[size].[format]

                    var filename     = imageId + appendedFileName + outputFormatString; //<-- [imageid][_xx].xxx
                    var fileNameFull = folderName + "/" + filename;                     //<-- /applicationimages/[imageid][_xx].xxx

                    //Size processingSize = new Size(formatWidth, formatHeight);
                    var resizeLayer = new ResizeLayer(processingSize)
                    {
                        ResizeMode = ResizeMode.Crop, AnchorPosition = AnchorPosition.Center
                    };


                    using (MemoryStream outStream = new MemoryStream())
                    {
                        using (ImageFactory imageFactory = new ImageFactory())
                        {
                            // Load, resize, set the format and quality and save an image.
                            // Applies all in order...
                            sourceStream.Position = 0; //<-- Have to set position to 0 to makse sure imageFactory.Load starts from the begining.
                            imageFactory.Load(sourceStream);

                            if (imageCropCoordinates != null)
                            {
                                var cropLayer = new ImageProcessor.Imaging.CropLayer(imageCropCoordinates.Left, imageCropCoordinates.Top, imageCropCoordinates.Right, imageCropCoordinates.Bottom, CropMode.Pixels);
                                //var cropRectangle = new Rectangle(imageCropCoordinates.Top, imageCropCoordinates.Left);

                                imageFactory.Crop(cropLayer);     //<-- Crop first
                                imageFactory.Resize(resizeLayer); //<-- Then resize
                            }
                            else
                            {
                                imageFactory.Resize(resizeLayer);//<-- Resize
                            }

                            //Convert to proper format
                            imageFactory.Format(outputFormatProcessorProperty);

                            if (imageEnhancementInstructions != null)
                            {
                                //Basics ---

                                if (imageEnhancementInstructions.Brightness != 0)
                                {
                                    imageFactory.Brightness(imageEnhancementInstructions.Brightness);
                                }
                                if (imageEnhancementInstructions.Contrast != 0)
                                {
                                    imageFactory.Contrast(imageEnhancementInstructions.Contrast);
                                }
                                if (imageEnhancementInstructions.Saturation != 0)
                                {
                                    imageFactory.Saturation(imageEnhancementInstructions.Saturation);
                                }

                                // Sharpness ---
                                if (imageEnhancementInstructions.Sharpen != 0)
                                {
                                    imageFactory.GaussianSharpen(imageEnhancementInstructions.Sharpen);
                                }


                                //Filters ----

                                if (imageEnhancementInstructions.Sepia == true)
                                {
                                    imageFactory.Filter(MatrixFilters.Sepia);
                                }

                                if (imageEnhancementInstructions.Polaroid == true)
                                {
                                    imageFactory.Filter(MatrixFilters.Polaroid);
                                }
                                if (imageEnhancementInstructions.Greyscale == true)
                                {
                                    imageFactory.Filter(MatrixFilters.GreyScale);
                                }
                            }

                            imageFactory.Save(outStream);
                        }


                        //Store image size to BLOB STORAGE ---------------------------------
                        #region BLOB STORAGE

                        //CloudBlobClient blobClient = Sahara.Core.Settings.Azure.Storage.StorageConnections.AccountsStorage.CreateCloudBlobClient();
                        CloudBlobClient blobClient = Settings.Azure.Storage.GetStoragePartitionAccount(storagePartition).CreateCloudBlobClient();

                        //Create and set retry policy
                        IRetryPolicy exponentialRetryPolicy = new ExponentialRetry(TimeSpan.FromMilliseconds(400), 6);
                        blobClient.DefaultRequestOptions.RetryPolicy = exponentialRetryPolicy;

                        //Creat/Connect to the Blob Container
                        blobClient.GetContainerReference(accountId).CreateIfNotExists(BlobContainerPublicAccessType.Blob); //<-- Create and make public
                        CloudBlobContainer blobContainer = blobClient.GetContainerReference(accountId);

                        //Get reference to the picture blob or create if not exists.
                        CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(fileNameFull);


                        if (type == "gif")
                        {
                            blockBlob.Properties.ContentType = "image/gif";
                        }
                        else if (type == "png")
                        {
                            blockBlob.Properties.ContentType = "image/png";
                        }
                        else
                        {
                            blockBlob.Properties.ContentType = "image/jpg";
                        }

                        //Save to storage
                        //Convert final BMP to byteArray
                        Byte[] finalByteArray;

                        finalByteArray = outStream.ToArray();

                        blockBlob.UploadFromByteArray(finalByteArray, 0, finalByteArray.Length);

                        #endregion
                    }

                    #endregion
                }
            }
Ejemplo n.º 22
0
        public static async Task GenerateKilledPictureAsync(string year, string month, byte[] source, byte[] avatar,
                                                            string battleName, string killedName,
                                                            string clanName, string killReason, Stream outPutStream)
        {
            using var font    = new FontFamily("方正兰亭黑简体");
            using var factory = new ImageFactory();
            factory.Load(source)
            .Watermark(new TextLayer
            {
                Text       = year,
                FontFamily = font,
                FontSize   = 24,
                FontColor  = Color.Black,
                Position   = new Point(217, 273)
            })
            .Watermark(new TextLayer
            {
                Text       = month,
                FontFamily = font,
                FontSize   = 24,
                FontColor  = Color.Black,
                Position   = new Point(340, 273)
            })
            .Watermark(new TextLayer
            {
                Text       = battleName,
                FontFamily = font,
                FontSize   = 24,
                FontColor  = Color.Black,
                Position   = new Point(427, 273)
            })
            .Watermark(new TextLayer
            {
                Text       = clanName,
                FontFamily = font,
                FontSize   = 20,
                FontColor  = Color.Black,
                Position   = new Point(180, 323)
            })
            .Watermark(new TextLayer
            {
                Text       = killedName,
                FontFamily = font,
                FontSize   = 24,
                FontColor  = Color.White,
                DropShadow = true,
                Position   = new Point(112, 229)
            })
            .Watermark(new TextLayer
            {
                Text       = killReason,
                FontFamily = font,
                FontSize   = 24,
                FontColor  = Color.Black,
                Position   = new Point(107, 400)
            });
            if (avatar != null)
            {
                await using var ms  = new MemoryStream();
                using var avatarImg = new ImageFactory();
                avatarImg.Load(avatar)
                .Resize(new Size(120, 120))
                .Format(new BitmapFormat())
                .Save(ms);
                ms.Seek(0, SeekOrigin.Begin);
                var srcImage = new Bitmap(ms);
                var dstImage = new Bitmap(srcImage.Width, srcImage.Height, PixelFormat.Format64bppArgb);
                var g        = Graphics.FromImage(dstImage);
                using var br = new SolidBrush(Color.Transparent);
                g.FillRectangle(br, 0, 0, dstImage.Width, dstImage.Height);

                var path = new GraphicsPath();
                path.AddEllipse(0, 0, dstImage.Width, dstImage.Height);
                g.SetClip(path);
                g.DrawImage(srcImage, 0, 0);

                factory.Overlay(new ImageLayer {
                    Image = dstImage, Position = new Point(60, 90)
                });
            }

            factory.Format(new JpegFormat())
            .Save(outPutStream);
        }
Ejemplo n.º 23
0
        private void Start_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
restart:
            foreach (string filename in Filenames)
            {
                byte[] photoBytes            = File.ReadAllBytes(filename);
                ISupportedImageFormat format = new JpegFormat();
                using (MemoryStream inStream = new MemoryStream(photoBytes))
                {
                    string[] temp           = filename.Split(new Char[] { '\\' });
                    string   tempe          = temp.Last();
                    string   outputFileName = string.Format("E:\\res\\{0}", tempe);
                    string   quote          = quotes[new Random().Next(0, quotes.Length)];
                    using (MemoryStream outStream = new MemoryStream())
                    {
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory())
                        {
                            // Load, resize, set the format and quality and save an image.
                            if (BlackWhite.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.BlackWhite;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = this.fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (Comic.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.Comic;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (HiSatch.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.HiSatch;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = this.fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (LoSatch.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.LoSatch;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (Polaroid.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.Polaroid;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (GreyScale.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.GreyScale;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (Gotham.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.Gotham;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                            else if (Sepia.Checked)
                            {
                                IMatrixFilter filter = MatrixFilters.Sepia;
                                imageFactory.Load(inStream);
                                imageFactory.Filter(filter);
                                imageFactory.Format(format);
                                imageFactory.Watermark(new TextLayer
                                {
                                    FontFamily = new FontFamily("Arial"),
                                    FontSize   = fontsize,
                                    Position   = new Point(xpos, ypos),
                                    Opacity    = opacity,
                                    DropShadow = shadow,
                                    Text       = quote
                                });
                                imageFactory.Save(outputFileName);
                                wallpaper.SetDesktopWallpaper(outputFileName);
                            }
                        }
                        // Do something with the stream.
                    }
                }
                //wallpaper.SetDesktopWallpaper(filename);
                Thread.Sleep(value);
                if (Filenames.Last() == filename)
                {
                    goto restart;
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            string format = this.DynamicParameter;
            ImageFormat imageFormat;
            switch (format)
            {
                case "png":
                    imageFormat = ImageFormat.Png;
                    break;
                case "bmp":
                    imageFormat = ImageFormat.Bmp;
                    break;
                case "gif":
                    imageFormat = ImageFormat.Gif;
                    break;
                default:
                    // Should be a jpeg.
                    imageFormat = ImageFormat.Jpeg;
                    break;
            }

            // Set the internal property.
            factory.Format(imageFormat);

            return factory.Image;
        }
Ejemplo n.º 25
0
        public Thumbnail GetThumbnailPhoto(string username, Format format)
        {
            byte[] bytes;

            var result = GetUser(username);

            if (result == null)
            {
                return(null);
            }

            using (var user = result.GetUnderlyingObject() as DirectoryEntry)
            {
                bytes = user.Properties["thumbnailPhoto"].Value as byte[];
            }

            if (bytes == null)
            {
                return(null);
            }

            using (var inStream = new MemoryStream(bytes))
                using (var outStream = new MemoryStream())
                {
                    using (var imageFactory = new ImageFactory())
                    {
                        const int imageQuality = 95;

                        imageFactory.Load(inStream);

                        switch (format)
                        {
                        case Format.Jpg:
                            imageFactory.Format(new JpegFormat());
                            break;

                        case Format.Png:
                            imageFactory.Format(new PngFormat());
                            break;

                        case Format.Gif:
                            imageFactory.Format(new GifFormat());
                            break;

                        case Format.Bmp:
                            imageFactory.Format(new BitmapFormat());
                            break;
                        }

                        imageFactory.Quality(imageQuality);
                        imageFactory.Save(outStream);
                    }

                    outStream.Position = 0;

                    var thumbnail = new Thumbnail()
                    {
                        Name          = username,
                        Format        = format,
                        ThumbnailData = outStream.ToArray()
                    };

                    return(thumbnail);
                }
        }
Ejemplo n.º 26
0
        public unsafe static void GetIndexedItem(Image img, PalFile pal, int maxNum, int mode = 2)
        {
            List <int> myPalette = new List <int>();

            if (img.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                foreach (Color c in img.Palette.Entries)
                {
                    myPalette.Add(c.ToArgb());
                }
            }
            else
            {
                switch (mode)
                {
                case 0:     // Even
                    HashSet <int> _set    = new HashSet <int>();
                    Bitmap        pic     = new Bitmap(img);
                    BitmapData    picData = pic.LockBits(
                        new Rectangle(0, 0, pic.Width, pic.Height),
                        ImageLockMode.ReadWrite,
                        PixelFormat.Format32bppArgb
                        );
                    byte *__ptr = (byte *)picData.Scan0;
                    for (int j = 0; j < pic.Height; ++j)
                    {
                        for (int i = 0; i < pic.Width; ++i)
                        {
                            int argb = Color.FromArgb(252, __ptr[2], __ptr[1], __ptr[0]).ToArgb();
                            _set.Add(argb);
                            __ptr += 4;
                        }
                        __ptr += picData.Stride - picData.Width * 4;
                    }
                    int STEP = 1;
                    while (_set.Count > 255)
                    {
                        var setarr = _set.ToArray();
                        foreach (int argb in setarr)
                        {
                            Color clr = Color.FromArgb(argb);
                            int   nR  = clr.R / (int)Math.Pow(8, STEP) * (int)Math.Pow(8, STEP);
                            int   nG  = clr.G / (int)Math.Pow(8, STEP) * (int)Math.Pow(8, STEP);
                            int   nB  = clr.B / (int)Math.Pow(4, STEP) * (int)Math.Pow(4, STEP);
                            clr = Color.FromArgb(252, nR, nG, nB);
                        }
                        _set.Clear();
                        foreach (int argb in setarr)
                        {
                            _set.Add(argb);
                        }
                        ++STEP;
                    }
                    myPalette = _set.ToList();
                    break;

                case 1:     // Frequency
                {
                    Dictionary <int, int> filt = new Dictionary <int, int>();
                    Bitmap     tmp             = new Bitmap(img);
                    BitmapData tmpData         = tmp.LockBits(
                        new Rectangle(0, 0, tmp.Width, tmp.Height),
                        ImageLockMode.ReadWrite,
                        PixelFormat.Format32bppArgb
                        );
                    byte *_ptr = (byte *)tmpData.Scan0;
                    for (int j = 0; j < tmp.Height; ++j)
                    {
                        for (int i = 0; i < tmp.Width; ++i)
                        {
                            int argb = Color.FromArgb(252, _ptr[2], _ptr[1], _ptr[0]).ToArgb();
                            if (filt.ContainsKey(argb))
                            {
                                ++filt[argb];
                            }
                            else
                            {
                                filt[argb] = 1;
                            }
                            _ptr += 4;
                        }
                        _ptr += tmpData.Stride - tmpData.Width * 4;
                    }
                    var retarr = filt.ToArray();
                    retarr.OrderByDescending(a => a.Value);
                    int cnt = Math.Min(255, retarr.Count());
                    for (int i = 0; i <= cnt; ++i)
                    {
                        myPalette.Add(retarr[i].Key);
                    }
                }
                break;

                case 2:     // Mid Cut
                default:
                    HashSet <int> set     = new HashSet <int>();
                    ImageFactory  factory = new ImageFactory();
                    factory.Load(img);
                    ISupportedImageFormat format = new PngFormat {
                        Quality = 100, IsIndexed = true, Quantizer = new OctreeQuantizer(maxNum, 8)
                    };
                    factory.Format(format);
                    MemoryStream stream = new MemoryStream();
                    factory.Save(stream);
                    img = Image.FromStream(stream);
                    stream.Dispose();
                    Bitmap     src     = new Bitmap(img);
                    Rectangle  rect    = new Rectangle(0, 0, src.Width, src.Height);
                    BitmapData bmpData = src.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
                    byte *     ptr     = (byte *)bmpData.Scan0;
                    for (int j = 0; j < src.Height; j++)
                    {
                        for (int i = 0; i < src.Width; i++)
                        {
                            int argb = Color.FromArgb(252, ptr[2], ptr[1], ptr[0]).ToArgb();
                            set.Add(argb);
                            ptr += 4;
                        }
                        ptr += bmpData.Stride - bmpData.Width * 4;
                    }
                    src.UnlockBits(bmpData);
                    img       = src;
                    myPalette = set.ToList();
                    break;
                }
            }
            while (myPalette.Count < 256)
            {
                myPalette.Add(Constant.Colors.PaletteBlack);
            }
            pal.Data = myPalette;
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            if (args.Length >= 3)
            {
                string pngPath      = args[0];
                string assetsFolder = args[1];
                string stickerPack  = args[2];

                // Are the argument file and folder valid?
                if (!File.Exists(pngPath) || !Directory.Exists(assetsFolder))
                {
                    Console.WriteLine("[ ! ] Invalid argument");
                    return;
                }

                // Acquire file name without extension and the folder where the converted sticker should be stored
                string baseName = Path.GetFileName(pngPath);
                baseName = baseName.Substring(0, baseName.LastIndexOf('.'));
                string webpFolder = Path.Combine(assetsFolder, stickerPack);

                Console.WriteLine("[ * ] Generating sticker from: {0}", pngPath);

                // Is a PNG?
                if (!pngPath.EndsWith(".png"))
                {
                    Console.WriteLine("[ ! ] File is not a PNG");
                    return;
                }

                // Is a 512x512 image?
                using (var image = System.Drawing.Image.FromFile(pngPath))
                {
                    if (image.Width != 512 || image.Height != 512)
                    {
                        Console.WriteLine("[ ! ] Invalid sticker size, should be 512x512");
                        return;
                    }
                }

                string tmpPath = Path.Combine(webpFolder, baseName + ".tmp");

                // Optimize PNG image
                var compressor = new PNGCompressor();
                compressor.CompressImageLossy(pngPath, tmpPath);

                // Convert to WebP
                var newName = baseName + ".webp";
                using (var imageFactory = new ImageFactory(preserveExifData: false))
                {
                    ISupportedImageFormat webp = new WebPFormat {
                        Quality = 75
                    };
                    imageFactory.Load(tmpPath);
                    imageFactory.Format(webp);
                    imageFactory.Save(Path.Combine(webpFolder, newName));
                }

                Console.WriteLine("[ * ] Saved WebP to: {0}", webpFolder);

                // Delete compressed temporary file
                if (File.Exists(tmpPath))
                {
                    File.Delete(tmpPath);
                }

                // Add to JSON
                JObject stickerJson = JObject.Parse(File.ReadAllText(Path.Combine(assetsFolder, "contents.json")));
                foreach (var pack in stickerJson["sticker_packs"])
                {
                    if (pack["identifier"].ToString() == stickerPack)
                    {
                        JObject sticker = new JObject();
                        sticker["image_file"] = newName;
                        sticker["emojis"]     = new JArray();

                        JArray stickers = (JArray)pack["stickers"];
                        stickers.Add(sticker);
                    }
                }
                File.WriteAllText(Path.Combine(assetsFolder, "contents.json"), stickerJson.ToString());
            }
            else
            {
                Console.WriteLine(".\\ZapArtist.exe <png image> <asset folder> <sticker pack>");
            }
        }
        internal static void Go(string path)
        {
            int filesProcessed = 0;
            int filesWritten   = 0;
            int filesSkipped   = 0;

            if (string.IsNullOrWhiteSpace(path))
            {
                path = Path.GetDirectoryName(typeof(Program).Assembly.Location);
            }

            DirectoryInfo dir = new DirectoryInfo(path);

            Console.WriteLine(Properties.Resources.ProcessBegin, dir.FullName);

            /* "Supported" extensions. Actually we support a lot more (via TagLibSharp).
             * However these are sufficient for me. You may add any other extension you like.
             */
            IList <string> extensions = new List <string>();

            extensions.Add(WildcardMp3);
            extensions.Add(WildcardFlac);

            foreach (string ext in extensions)
            {
                Console.WriteLine(Properties.Resources.ProcessingWildcardNow, ext);

                IEnumerable <FileInfo> files = dir.EnumerateFiles(ext, SearchOption.AllDirectories);

                foreach (FileInfo file in files)
                {
                    filesProcessed++;

                    DirectoryInfo fileDir   = file.Directory;
                    FileInfo      folderJpg = new FileInfo(Path.Combine(fileDir.FullName, FolderJpgFileName));

                    if (folderJpg.Exists)
                    {
                        filesSkipped++;
                        continue;
                    }

                    var taggedFile = TagLib.File.Create(file.FullName);

                    IPicture[] pictures = taggedFile.Tag.Pictures;
                    IPicture   pic      = pictures.FirstOrDefault(_ => _.Type == PictureType.FrontCover) ?? pictures.FirstOrDefault();

                    if (pic == null)
                    {
                        continue;
                    }

                    using (MemoryStream srcImgStream = new MemoryStream(pic.Data.Data))
                    {
                        _fac.Load(srcImgStream);
                        _fac.Format(new JpegFormat());

                        using (FileStream fs = new FileStream(folderJpg.FullName, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            _fac.Save(fs);
                        }

                        filesWritten++;
                    }
                }
            }

            Console.WriteLine(Properties.Resources.ProcessFinished, filesProcessed, filesSkipped, filesWritten);
        }