public static BitmapImage CropImage(byte[] photoBytes, CropLayer cropLayer)
        {
            BitmapImage bitmap = new BitmapImage();

            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                    {
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(inStream);
                        imageFactory.Crop(cropLayer);
                        imageFactory.Save(outStream);
                    }
                    // Do something with the stream.
                    bitmap.BeginInit();
                    bitmap.StreamSource = outStream;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }

            return(bitmap);
        }
Esempio n. 2
0
        public byte[] Transform(byte[] img, TransformationParametrs parametrs)
        {
            byte[]    result;
            Rectangle cropRectangle = new Rectangle(parametrs.TopLeftConerX, parametrs.TopLeftConerY, parametrs.Width, parametrs.Height);

            if (cropRectangle.Width == 0 || cropRectangle.Height == 0)
            {
                throw new ArgumentOutOfRangeException("Пустая область");
            }
            using (MemoryStream outStream = new MemoryStream())
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                {
                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(img);
                    if (imageFactory.Image.Width > 1000 || imageFactory.Image.Height > 1000)
                    {
                        throw new ArgumentException("Слишком большое изображение");
                    }
                    if (parametrs.Flip != Flip.None)
                    {
                        if (parametrs.Flip == Flip.Horizontal)
                        {
                            imageFactory.Flip(false);
                        }
                        else
                        {
                            imageFactory.Flip(true);
                        }
                    }
                    if (parametrs.Rotation != Rotation.None)
                    {
                        if (parametrs.Rotation == Rotation.Clockwise)
                        {
                            imageFactory.Rotate(90);
                        }
                        else
                        {
                            imageFactory.Rotate(-90);
                        }
                    }
                    try
                    {
                        imageFactory.Crop(cropRectangle);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        throw new ArgumentOutOfRangeException("Пустая область");
                    }
                    imageFactory.Save(outStream);
                }

                // Do something with the stream.
                result = outStream.ToArray();
            }

            return(result);
        }
Esempio n. 3
0
 private void Crop(ImageFactory imageFactory, ProcessingParameters parameters)
 {
     if (parameters.CropPercentX == 0 && parameters.CropPercentY == 0)
     {
         return;
     }
     imageFactory.Crop(new CropLayer(0, 0, parameters.CropPercentX, parameters.CropPercentY, CropMode.Percentage));
 }
Esempio n. 4
0
        /// <summary>
        /// 将给定图片从中心点周围裁剪出指定大小的图片
        /// </summary>
        /// <param name="factory">包含给定图片的工厂类对象</param>
        /// <param name="size">需要裁剪的尺寸</param>
        /// <returns>从原图片中裁剪出来的新图片二进制流</returns>
        private static Stream CropAroundCenterPoint(ImageFactory factory, Size size)
        {
            MemoryStream outStream = new MemoryStream();

            var cropArea = GetCropAreaAroundCenterPoint(factory.Image.Size, size);

            factory.Crop(cropArea)
            .Save(outStream);

            return(outStream);
        }
Esempio n. 5
0
        private void CropBtn_Click(object sender, EventArgs e)
        {
            int myImageWidth  = imgFactory.Image.Width;
            int myImageHeight = imgFactory.Image.Height;

            int       newIntValueW = Convert.ToInt32(WidthResTbox.Text);
            int       newIntValueH = Convert.ToInt32(HeightResTbox.Text);
            Rectangle rec          = new Rectangle(new Point(myImageWidth / 2, myImageHeight / 2), new Size(newIntValueW, newIntValueH));

            imgFactory.Crop(rec);
            Close();
        }
        public static string ImageProcessorRotateAutoCrop(string imageFullPath, float angle, QwantImage image)
        {
            Logger logger = LogManager.GetCurrentClassLogger();

            string imageDir       = Path.GetDirectoryName(imageFullPath);
            string resultFileName = $"{imageDir}\\{Path.GetFileNameWithoutExtension(imageFullPath)}_result.jpg";

            try
            {
                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    imageFactory
                    .Load(imageFullPath)
                    .Flip();

                    int w = imageFactory.Image.Width;
                    int h = imageFactory.Image.Height;

                    logger.Info($"- пост-обработка изображения, входное разрешение {w}x{h}");

                    int h1 = Convert.ToInt32(Math.Round(w * Math.Sin((angle / 180D) * Math.PI)));
                    int w1 = Convert.ToInt32(Math.Round(h * Math.Sin((angle / 180D) * Math.PI)));

                    imageFactory.Rotate(angle);

                    int newW = imageFactory.Image.Width;
                    int newH = imageFactory.Image.Height;

                    ImageProcessor.Imaging.CropLayer cropLayer = new ImageProcessor.Imaging.CropLayer(
                        w1, h1, newW - 2 * w1, newH - 2 * h1, ImageProcessor.Imaging.CropMode.Pixels);

                    imageFactory
                    .Crop(cropLayer)
                    .Save(resultFileName);

                    image.width  = imageFactory.Image.Width;
                    image.height = imageFactory.Image.Height;
                    logger.Info($"- пост-обработка завершена, выходное разрешение {imageFactory.Image.Width}x{imageFactory.Image.Height}");

                    return(resultFileName);
                }
            }
            catch (Exception ex)
            {
                logger.Error($"- ошибка пост-обработки: {ex.Message}");
            }

            return(string.Empty);
        }
        /// <summary>
        /// 进行截图处理
        /// </summary>
        /// <param name="srcimg">原图像对象</param>
        /// <param name="cropRect">截图区域</param>
        /// <param name="cropimg">截图结果</param>
        private void CropImage(Bitmap srcimg, Rectangle cropRect, out Bitmap cropimg)
        {
            cropimg = null;
            // 加载图像
            ImageFactory imgFactory = new ImageFactory();

            using (MemoryStream m = new MemoryStream())
            {
                srcimg.Save(m, ImageFormat.Jpeg);
                imgFactory.Load(m);
            }

            imgFactory.Crop(cropRect);

            using (MemoryStream stream = new MemoryStream())
            {
                imgFactory.Save(stream);
                Image result = Image.FromStream(stream);
                cropimg = new Bitmap(result);
            }
        }
Esempio n. 8
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...");
                        }
                    }
                });
            });
        }
        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
                }
            }
Esempio n. 10
0
        public List <FileResultModel> CropSaveProfile([FromBody] CropImage body)
        {
            try
            {
                var filename      = body.Filename;
                var yCropPosition = body.yCrop;
                var portal        = PortalController.GetCurrentPortalSettings();
                var user          = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
                var userProperty  = new UserPropertyComponent(user.UserID);
                if (user.IsInRole("Registered Users"))
                {
                    if (userProperty.UserProperty.ProfilePicture.GetValueOrDefault(Guid.Empty) == Guid.Empty)
                    {
                        userProperty.UserProperty.ProfilePicture = Guid.NewGuid();
                        if (userProperty.Save() <= 0)
                        {
                            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
                        }
                    }

                    var fileResultModelList = new List <FileResultModel>();
                    yCropPosition = yCropPosition * -1;
                    string       extension             = ".png";//Path.GetExtension(filename);
                    string       fileRootName          = userProperty.UserProperty.ProfilePicture.ToString();
                    MemoryStream outStream             = new MemoryStream();
                    long         tmpSize               = 0;
                    string       ImageProcessingFolfer = Path.Combine(portal.HomeDirectoryMapPath + "ModIma\\TempUserImages", filename);

                    ImageFactory imageFactory = new ImageFactory(preserveExifData: true);
                    imageFactory.Load(ImageProcessingFolfer);
                    imageFactory.Save(outStream);// ();
                    tmpSize = outStream.Length;
                    Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "ModIma\\UserProfileImages", fileRootName + extension));
                    fileResultModelList.Add(new FileResultModel()
                    {
                        Extension   = extension,
                        Filename    = fileRootName,
                        Link        = portal.HomeDirectory + "ModIma/UserProfileImages/" + fileRootName + extension,
                        Description = "Original Image",
                        Size        = tmpSize
                    });
                    var   image           = imageFactory.Image;
                    var   originalHeight  = image.Size.Height;
                    var   originalWidth   = image.Size.Width;
                    float referenceHeight = 512;
                    float referenceWidth  = 512;
                    float WidthFactor     = 1;
                    WidthFactor = referenceWidth / originalWidth;
                    float HeightFactor = 1;
                    HeightFactor = referenceHeight / originalHeight;
                    float standardHeight = 0;
                    standardHeight = originalHeight * WidthFactor;
                    float     cutTop        = Convert.ToSingle(yCropPosition) / WidthFactor;
                    float     cutBotom      = (standardHeight - referenceHeight - cutTop) / WidthFactor;
                    Size      sizeCrop      = new Size(Convert.ToInt32(referenceWidth / WidthFactor), Convert.ToInt32(referenceHeight / WidthFactor));
                    Point     pointCrop     = new Point(0, Convert.ToInt32(cutTop));
                    Rectangle rectangleCrop = new Rectangle(pointCrop, sizeCrop);
                    imageFactory.Crop(rectangleCrop);
                    System.Drawing.Size sizeBig = new System.Drawing.Size(Convert.ToInt32(referenceWidth), Convert.ToInt32(referenceHeight));
                    imageFactory.Resize(sizeBig);
                    outStream = new MemoryStream();
                    imageFactory.Save(outStream);
                    tmpSize = outStream.Length;
                    Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "ModIma\\UserProfileImages", "cropBig" + fileRootName + extension));
                    fileResultModelList.Add(new FileResultModel()
                    {
                        Extension   = extension,
                        Filename    = "cropBig" + fileRootName,
                        Link        = portal.HomeDirectory + "ModIma/UserProfileImages/" + "cropBig" + fileRootName + extension,
                        Description = "Crop Big",
                        Size        = tmpSize
                    });
                    System.Drawing.Size sizeSmall = new System.Drawing.Size(Convert.ToInt32(300), Convert.ToInt32(300));
                    imageFactory.Resize(sizeSmall);
                    outStream = new MemoryStream();
                    imageFactory.Save(outStream);
                    tmpSize = outStream.Length;
                    Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "ModIma\\UserProfileImages", "cropThumb" + fileRootName + extension));
                    fileResultModelList.Add(new FileResultModel()
                    {
                        Extension   = extension,
                        Filename    = "cropThumb" + fileRootName,
                        Link        = portal.HomeDirectory + "ModIma/UserProfileImages/" + "cropThumb" + fileRootName + extension,
                        Description = "Crop Thumbnail",
                        Size        = tmpSize
                    });
                    Helper.HelperMethods.DeleteFiles(portal.HomeDirectoryMapPath + "ModIma\\TempUserImages", filename);
                    return(fileResultModelList);
                }
                else
                {
                    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }
            }
            catch (HttpResponseException e)
            {
                throw e;
            }
            catch (Exception ee)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ee);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 11
0
 public IImageTransformer Crop(Rectangle rect)
 {
     _image.Crop(rect);
     return(this);
 }
Esempio n. 12
0
        public List <FileResultModel> CropSaveBanner([FromUri] Guid organizationId, [FromBody] CropImage body)
        {
            try
            {
                var filename      = body.Filename;
                var yCropPosition = body.yCrop;
                var organization  = new OrganizationComponent(organizationId);
                var portal        = PortalController.GetCurrentPortalSettings();
                var currentUser   = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo();
                var tempId        = Helper.HelperMethods.GenerateHash(currentUser.UserID).ToString();
                if (currentUser.IsInRole("Registered Users"))
                {
                    if (currentUser.IsInRole("Administrators") || organization.Organization.CreatedBy == DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo().UserID)
                    {
                        var fileResultModelList = new List <FileResultModel>();
                        yCropPosition = yCropPosition * -1;
                        string       extension             = ".png";//Path.GetExtension(filename);
                        string       fileRootName          = organizationId.ToString();
                        MemoryStream outStream             = new MemoryStream();
                        long         tmpSize               = 0;
                        string       ImageProcessingFolfer = Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\TempImages", filename);
                        Helper.HelperMethods.DeleteFiles(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "*" + organizationId.ToString() + "*");
                        ImageFactory imageFactory = new ImageFactory(preserveExifData: true);
                        imageFactory.Load(ImageProcessingFolfer);
                        imageFactory.Save(outStream);// ();
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", fileRootName + extension));


                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + fileRootName + extension,
                            Description = "Original Image",
                            Size        = tmpSize
                        });



                        var   image           = imageFactory.Image;
                        var   originalHeight  = image.Size.Height;
                        var   originalWidth   = image.Size.Width;
                        float referenceHeight = 575;
                        float referenceWidth  = 1148;
                        float WidthFactor     = 1;
                        WidthFactor = referenceWidth / originalWidth;
                        float HeightFactor = 1;
                        HeightFactor = referenceHeight / originalHeight;
                        float standardHeight = 0;
                        standardHeight = originalHeight * WidthFactor;
                        float     cutTop        = Convert.ToSingle(yCropPosition) / WidthFactor;
                        float     cutBotom      = (standardHeight - referenceHeight - cutTop) / WidthFactor;
                        Size      sizeCrop      = new Size(Convert.ToInt32(referenceWidth / WidthFactor), Convert.ToInt32(referenceHeight / WidthFactor));
                        Point     pointCrop     = new Point(0, Convert.ToInt32(cutTop));
                        Rectangle rectangleCrop = new Rectangle(pointCrop, sizeCrop);
                        imageFactory.Crop(rectangleCrop);
                        System.Drawing.Size sizeBig = new System.Drawing.Size(Convert.ToInt32(referenceWidth), Convert.ToInt32(referenceHeight));
                        var img = imageFactory.Resize(sizeBig);


                        outStream = new MemoryStream();
                        imageFactory.Save(outStream);
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "cropBig" + fileRootName + extension));
                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = "cropBig" + fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + "cropBig" + fileRootName + extension,
                            Description = "Crop Big",
                            Size        = tmpSize
                        });


                        System.Drawing.Size sizeSmall = new System.Drawing.Size(Convert.ToInt32(600), Convert.ToInt32(300));
                        imageFactory.Resize(sizeSmall);
                        outStream = new MemoryStream();
                        imageFactory.Save(outStream);
                        tmpSize = outStream.Length;
                        Helper.HelperMethods.SaveImage(ref outStream, Path.Combine(portal.HomeDirectoryMapPath + "OrgImages\\HeaderImages", "cropThumb" + fileRootName + extension));



                        fileResultModelList.Add(new FileResultModel()
                        {
                            Extension   = extension,
                            Filename    = "cropThumb" + fileRootName,
                            Link        = portal.HomeDirectory + "OrgImages/HeaderImages/" + "cropThumb" + fileRootName + extension,
                            Description = "Crop Thumbnail",
                            Size        = tmpSize
                        });
                        Helper.HelperMethods.DeleteFiles(portal.HomeDirectoryMapPath + "OrgImages\\TempUserImages", filename + "*");
                        return(fileResultModelList);
                    }
                    else
                    {
                        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                    }
                }
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
            catch (HttpResponseException e)
            {
                throw e;
            }
            catch (Exception ee)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(ee);
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 13
0
 public override void Apply(ImageFactory fs)
 {
     fs = fs.Crop(new CropLayer(_left, _top, _right, _bottom, CropMode.Percentage));
 }
Esempio n. 14
0
        private void goGenerateProcessesFriendship()
        {
            int artOfficial = Process.GetProcesses().Length;

            /* Previous code for tallying after we get the processes...which is just a waste of time. Still, it's here.
             * foreach (var theProcess in Process.GetProcesses())
             * {
             *  if (theProcess.MainWindowTitle != "" && theProcess.MainWindowTitle != "Space")
             *  {
             *      artOfficial++;
             *  }
             * }*/


            if (artOfficial != currentCountProc)
            {
                spaceForProcesses.Controls.Clear();
                int procCount = 0;
                foreach (var theProcess in Process.GetProcesses())
                {
                    if (procCount != 0 && procCount != 4)
                    {
                        if ((theProcess.MainWindowTitle != "" && theProcess.Modules[0].FileName != "ProjectSnowshoes.exe") && theProcess.MainWindowHandle != null)
                        {
                            foreach (var h in getHandles(theProcess))
                            {
                                if (IsWindowVisible(h))
                                {
                                    PictureBox    hmGreatJobFantasticAmazing = new PictureBox();
                                    StringBuilder sb = new StringBuilder(GetWindowTextLength(h) + 1);
                                    GetWindowText(h, sb, sb.Capacity);



                                    hmGreatJobFantasticAmazing.Margin   = new Padding(6, 0, 6, 0);
                                    hmGreatJobFantasticAmazing.Visible  = true;
                                    hmGreatJobFantasticAmazing.SizeMode = PictureBoxSizeMode.CenterImage;
                                    hmGreatJobFantasticAmazing.BackgroundImageLayout = ImageLayout.Zoom;

                                    Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap().Save(@"C:\ProjectSnowshoes\temptaskico.png");

                                    ImageFactory grayify = new ImageFactory();
                                    grayify.Load(@"C:\ProjectSnowshoes\temptaskico.png");
                                    Size sizeeeee = new System.Drawing.Size();
                                    sizeeeee.Height = 20;
                                    sizeeeee.Width  = 20;
                                    ImageProcessor.Imaging.ResizeLayer reLay = new ImageProcessor.Imaging.ResizeLayer(sizeeeee);
                                    grayify.Resize(reLay);

                                    hmGreatJobFantasticAmazing.Image  = grayify.Image;
                                    hmGreatJobFantasticAmazing.Click += (sender, args) =>
                                    {
                                        ShowWindow(theProcess.MainWindowHandle, 5);
                                        ShowWindow(theProcess.MainWindowHandle, 9);
                                    };
                                    hmGreatJobFantasticAmazing.MouseHover += (sender, args) =>
                                    {
                                        Properties.Settings.Default.stayHere = true;
                                        Properties.Settings.Default.Save();
                                        int recordNao = hmGreatJobFantasticAmazing.Left;

                                        hmGreatJobFantasticAmazing.Image.Save(@"C:\ProjectSnowshoes\TheyNeedToKeepOriginalAlbums.png");
                                        Size sizeeeeeA = new System.Drawing.Size();
                                        sizeeeeeA.Height = 100;
                                        sizeeeeeA.Width  = 100;
                                        ImageProcessor.Imaging.ResizeLayer   reLayA = new ImageProcessor.Imaging.ResizeLayer(sizeeeeeA);
                                        ImageProcessor.Imaging.GaussianLayer gauLay = new ImageProcessor.Imaging.GaussianLayer();
                                        gauLay.Sigma     = 2;
                                        gauLay.Threshold = 10;
                                        gauLay.Size      = 20;
                                        ImageFactory backify = new ImageFactory();
                                        backify.Load(@"C:\ProjectSnowshoes\TheyNeedToKeepOriginalAlbums.png");
                                        backify.Brightness(-30);
                                        backify.Resize(reLayA);
                                        backify.GaussianBlur(gauLay);
                                        ImageProcessor.Imaging.CropLayer notAsLongAsOriginalName = new ImageProcessor.Imaging.CropLayer(90, 0, 0, 0, ImageProcessor.Imaging.CropMode.Percentage);
                                        backify.Crop(new Rectangle(25, (100 - this.Height) / 2, 50, this.Height));
                                        hmGreatJobFantasticAmazing.BackgroundImage = backify.Image;
                                        grayify.Save(@"C:\ProjectSnowshoes\TheyStillNeedToKeepOriginalAlbums.png");
                                        ImageFactory grayifyA = new ImageFactory();
                                        grayifyA.Load(@"C:\ProjectSnowshoes\TheyStillNeedToKeepOriginalAlbums.png");
                                        grayifyA.Saturation(44);
                                        grayifyA.Brightness(42);
                                        hmGreatJobFantasticAmazing.Image = grayifyA.Image;
                                        // Yeahhhhhhhhh I'm going to have to do this another way
                                        // panel1.Controls.Add(areYouSeriouslyStillDoingThisLetItGo);
                                        // Oh
                                        // I can just make another form to draw over and go have turnips with parameters
                                        // Also credits to Microsoft Word's "Sentence Case" option as this came out in all caps originally
                                        // Measuring string turnt-up-edness was guided by an answer on Stack Overflow by Tom Anderson.
                                        String   keepThisShortWeNeedToOptimize      = sb.ToString().Replace("&", "&&");
                                        Graphics heyGuessWhatGraphicsYeahThatsRight = Graphics.FromImage(new Bitmap(1, 1));
                                        SizeF    sure      = heyGuessWhatGraphicsYeahThatsRight.MeasureString(keepThisShortWeNeedToOptimize, new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular, GraphicsUnit.Point));
                                        Size     sureAgain = sure.ToSize();
                                        int      recordThatJim;
                                        if (sureAgain.Width >= 300)
                                        {
                                            recordThatJim = sureAgain.Width + 10;
                                        }
                                        else
                                        {
                                            recordThatJim = 300;
                                        }
                                        CanWeMakeAHoverFormLikeThisIsThisLegal notAsLongInstanceName = new CanWeMakeAHoverFormLikeThisIsThisLegal(recordNao + 150, this.Height, recordThatJim, keepThisShortWeNeedToOptimize);
                                        notAsLongInstanceName.Show();
                                        notAsLongInstanceName.BringToFront();
                                        //hmGreatJobFantasticAmazing.BringToFront();
                                        //panel1.Controls.Add(hmGreatJobFantasticAmazing);
                                        //hmGreatJobFantasticAmazing.Top = this.Top - 40;
                                        //hmGreatJobFantasticAmazing.Left = recordNao + 150;
                                        //hmGreatJobFantasticAmazing.BringToFront();
                                        //hmGreatJobFantasticAmazing.Invalidate();

                                        /*hmGreatJobFantasticAmazing.Height = 100;
                                         * hmGreatJobFantasticAmazing.Width = 100;*/
                                    };
                                    hmGreatJobFantasticAmazing.MouseLeave += (sender, args) =>
                                    {
                                        /*hmGreatJobFantasticAmazing.ImageAlign = ContentAlignment.MiddleCenter;
                                         * hmGreatJobFantasticAmazing.AutoEllipsis = false;
                                         * hmGreatJobFantasticAmazing.Width = 40;
                                         * hmGreatJobFantasticAmazing.BackColor = Color.Transparent;
                                         * //hmGreatJobFantasticAmazing.Font = new System.Drawing.Font(Properties.Settings.Default.fontsOfScience[Properties.Settings.Default.whoIsThisCrazyDoge], 14, FontStyle.Regular);
                                         * //hmGreatJobFantasticAmazing.ForeColor = Color.White;
                                         * hmGreatJobFantasticAmazing.TextAlign = ContentAlignment.MiddleLeft;
                                         * hmGreatJobFantasticAmazing.Text = "";*/
                                        try
                                        {
                                            Application.OpenForms["CanWeMakeAHoverFormLikeThisIsThisLegal"].Close();
                                        }
                                        catch (Exception exTurnip) { }
                                        hmGreatJobFantasticAmazing.BackgroundImage = null;
                                        hmGreatJobFantasticAmazing.Invalidate();
                                        Properties.Settings.Default.stayHere = false;
                                        Properties.Settings.Default.Save();
                                        hmGreatJobFantasticAmazing.Image = grayify.Image;
                                    };
                                    //openFileToolTip.SetToolTip(hmGreatJobFantasticAmazing, theProcess.MainWindowTitle);
                                    //hmGreatJobFantasticAmazing.BackgroundImage = Icon.ExtractAssociatedIcon(theProcess.Modules[0].FileName).ToBitmap();
                                    hmGreatJobFantasticAmazing.Height = this.Height;
                                    hmGreatJobFantasticAmazing.Width  = 50;
                                    spaceForProcesses.Controls.Add(hmGreatJobFantasticAmazing);
                                }
                            }
                        }
                    }
                    procCount++;
                }
            }

            currentCountProc = artOfficial;
        }
Esempio n. 15
0
        public static ImageFactory WeightedCrop(this ImageFactory imageFactory, Double targetAspectRatio, Point focalPoint)
        {
            Double focalX = focalPoint.X;
            Double focalY = focalPoint.Y;

            Double centerX = imageFactory.Image.Width / 2;
            Double centerY = imageFactory.Image.Height / 2;

            Boolean cropX = (imageFactory.Image.Width / imageFactory.Image.Height) > targetAspectRatio;

            Boolean leftHalf = (focalPoint.X < centerX);
            Boolean topHalf  = (focalPoint.Y < centerY);

            // How far around the center point do we expand for maximum coverage
            Double expandX = cropX ? centerX : (imageFactory.Image.Height * targetAspectRatio / 2);
            Double expandY = cropX ? (imageFactory.Image.Width / targetAspectRatio / 2) : centerY;

            // Ensure we're not too tall
            if (expandY > centerY)
            {
                expandY = centerY;
                expandX = expandY * targetAspectRatio;
            }

            // Ensure we're not too wide
            if (expandX > centerX)
            {
                expandX = centerX;
                expandY = expandX / targetAspectRatio;
            }

            if (focalX - expandX < 0)
            {
                focalX = expandX;
            }

            if (focalX + expandX > imageFactory.Image.Width)
            {
                focalX = imageFactory.Image.Width - expandX;
            }

            if (focalY - expandY < 0)
            {
                focalY = expandY;
            }

            if (focalY + expandY > imageFactory.Image.Height)
            {
                focalY = imageFactory.Image.Height - expandY;
            }

#if IMAGEPROCESSOR_BUGGED
            // The bugged version adds your initial point to your width calculation if you try to center your crops

            imageFactory.Crop(new CropLayer(
                                  Convert.ToSingle(focalX - expandX),
                                  Convert.ToSingle(focalY - expandY),
                                  imageFactory.Image.Width,
                                  imageFactory.Image.Height,
                                  CropMode.Pixels
                                  ));

            imageFactory.Crop(new CropLayer(
                                  0,
                                  0,
                                  Convert.ToSingle(expandX * 2),
                                  Convert.ToSingle(expandY * 2),
                                  CropMode.Pixels
                                  ));
#else
            imageFactory.Crop(new CropLayer(
                                  Convert.ToSingle(focalX - expandX),
                                  Convert.ToSingle(focalY - expandY),
                                  Convert.ToSingle(focalX + expandX),
                                  Convert.ToSingle(focalY + expandY),
                                  CropMode.Pixels
                                  );
#endif

            return(imageFactory);
        }