public void ThenResultingImageSizeShouldBeLikeCropLayer(float left, float top, float right, float bottom, CropMode mode) { // When crop mode is percentage. The right and bottom values should represent // the percentage amount to remove from those sides. const int SizeX = 200; const int SizeY = 200; int expectedWidth = 160; int expectedHeight = 144; CropLayer cl = new CropLayer(left, top, right, bottom, mode); // Arrange using (Bitmap bitmap = new Bitmap(SizeX, SizeY)) using (MemoryStream memoryStream = new MemoryStream()) { bitmap.Save(memoryStream, ImageFormat.Bmp); memoryStream.Position = 0; using (ImageFactory imageFactory = new ImageFactory()) using (ImageFactory resultImage = imageFactory.Load(memoryStream).Crop(cl)) { // Act // Assert Assert.AreEqual(expectedWidth, resultImage.Image.Width); Assert.AreEqual(expectedHeight, resultImage.Image.Height); } } }
public void MergeImage() { Bitmap img = new Bitmap(1024, 768, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); Image source1 = BytearrToImage(Input); Image source2 = BytearrToImage(OpenImage()); Rectangle Rec2 = new Rectangle(200, 300, source2.Width, source2.Height); g.DrawImage(source1, Rec); g.DrawImage(source2, Rec2); using (Process = new MemoryStream()) { img.Save(Process, System.Drawing.Imaging.ImageFormat.Png); img = new Bitmap(Process); Rec = SaveRecInfo(img); var crop = new ImageProcessor.Imaging.CropLayer(Rec.X, Rec.Y, Rec.Width, Rec.Height, CropMode.Pixels); using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(img) .Crop(crop) .Save(Process); } SaveProcess(); } }
public void ConstructorSavesData(float left, float top, float right, float bottom, CropMode mode) { CropLayer cl = new CropLayer(left, top, right, bottom, mode); cl.Left.Should().Be(left); cl.Top.Should().Be(top); cl.Right.Should().Be(right); cl.Bottom.Should().Be(bottom); cl.CropMode.Should().Be(mode); }
public void TestCropRegex() { const string Querystring = "crop=0,0,150,300"; CropLayer expected = new CropLayer(0, 0, 150, 300, CropMode.Pixels); Crop crop = new Crop(); crop.MatchRegexIndex(Querystring); CropLayer actual = crop.DynamicParameter; Assert.AreEqual(expected, actual); }
/// <summary> /// Determines whether the specified <see cref="System.Object" />, is /// equal to this instance. /// </summary> /// <param name="obj"> /// The <see cref="System.Object" /> to compare with this instance. /// </param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to /// this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { CropLayer cropLayer = obj as CropLayer; if (cropLayer == null) { return(false); } // Define the tolerance for variation in their values return(Math.Abs(this.Top - cropLayer.Top) <= Math.Abs(this.Top * .0001) && Math.Abs(this.Right - cropLayer.Right) <= Math.Abs(this.Right * .0001) && Math.Abs(this.Bottom - cropLayer.Bottom) <= Math.Abs(this.Bottom * .0001) && Math.Abs(this.Left - cropLayer.Left) <= Math.Abs(this.Left * .0001) && this.CropMode.Equals(cropLayer.CropMode)); }
public void CropTransparentImage() { using (Process = new MemoryStream()) { Rec = SaveRecInfo(new Bitmap(BytearrToImage(Input))); var crop = new ImageProcessor.Imaging.CropLayer(Rec.X, Rec.Y, Rec.Width, Rec.Height, CropMode.Pixels); using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(Input) .Crop(crop) .Save(Process); } SaveProcess(); } }
public void CropImage() { using (Process = new MemoryStream()) { Rec = new Rectangle(X, Y, W, H); var crop = new ImageProcessor.Imaging.CropLayer(Rec.X, Rec.Y, Rec.Width, Rec.Height, CropMode.Pixels); using (var imageFactory = new ImageFactory(preserveExifData: true)) { imageFactory.Load(Input) .Crop(crop) .Save(Process); } SaveProcess(); } }
/// <summary> /// The position in the original string where the first character of the captured substring was found. /// </summary> /// <param name="queryString"> /// The query string to search. /// </param> /// <returns> /// The zero-based starting position in the original string where the captured substring was found. /// </returns> public int MatchRegexIndex(string queryString) { this.SortOrder = int.MaxValue; Match match = this.RegexPattern.Match(queryString); if (match.Success) { this.SortOrder = match.Index; NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString); float[] coordinates = QueryParamParser.Instance.ParseValue<float[]>(queryCollection["crop"]); // Default CropMode.Pixels will be returned. CropMode cropMode = QueryParamParser.Instance.ParseValue<CropMode>(queryCollection["cropmode"]); CropLayer cropLayer = new CropLayer(coordinates[0], coordinates[1], coordinates[2], coordinates[3], cropMode); this.Processor.DynamicParameter = cropLayer; } return this.SortOrder; }
/// <summary> /// The position in the original string where the first character of the captured substring was found. /// </summary> /// <param name="queryString"> /// The query string to search. /// </param> /// <returns> /// The zero-based starting position in the original string where the captured substring was found. /// </returns> public int MatchRegexIndex(string queryString) { int index = 0; // Set the sort order to max to allow filtering. this.SortOrder = int.MaxValue; // First merge the matches so we can parse . StringBuilder stringBuilder = new StringBuilder(); foreach (Match match in this.RegexPattern.Matches(queryString)) { if (match.Success) { if (index == 0) { // Set the index on the first instance only. this.SortOrder = match.Index; } stringBuilder.Append(match.Value); index += 1; } } if (this.SortOrder < int.MaxValue) { // Match syntax string toParse = stringBuilder.ToString(); float[] coordinates = this.ParseCoordinates(toParse); CropMode cropMode = this.ParseMode(toParse); CropLayer cropLayer = new CropLayer(coordinates[0], coordinates[1], coordinates[2], coordinates[3], cropMode); this.DynamicParameter = cropLayer; } return this.SortOrder; }
/// <summary> /// Crops the current image to the given location and size. /// </summary> /// <param name="cropLayer"> /// The <see cref="Imaging.CropLayer"/> containing the coordinates and mode to crop the image with. /// </param> /// <returns> /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class. /// </returns> public ImageFactory Crop(CropLayer cropLayer) { if (this.ShouldProcess) { Crop crop = new Crop { DynamicParameter = cropLayer }; this.CurrentImageFormat.ApplyProcessor(crop.ProcessImage, this); } return this; }
/// <summary> /// Crops the current image to the given location and size. /// </summary> /// <param name="rectangle"> /// The <see cref="T:System.Drawing.Rectangle"/> containing the coordinates to crop the image to. /// </param> /// <returns> /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class. /// </returns> public ImageFactory Crop(Rectangle rectangle) { if (this.ShouldProcess) { CropLayer cropLayer = new CropLayer(rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height, CropMode.Pixels); return this.Crop(cropLayer); } return this; }
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 } }
/// <summary> /// Crops the current image to the given location and size. /// </summary> /// <param name="cropLayer"> /// The <see cref="T:CropLayer"/> containing the coordinates and mode to crop the image with. /// </param> /// <returns> /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class. /// </returns> public ImageFactory Crop(CropLayer cropLayer) { if (this.ShouldProcess) { Crop crop = new Crop { DynamicParameter = cropLayer }; this.Image = crop.ProcessImage(this); } return this; }
/// <summary> /// Crops the current image to the given location and size. /// </summary> /// <param name="rectangle"> /// The <see cref="T:System.Drawing.Rectangle"/> containing the coordinates to crop the image to. /// </param> /// <returns> /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class. /// </returns> public ImageFactory Crop(Rectangle rectangle) { if (this.ShouldProcess) { CropLayer cropLayer = new CropLayer(rectangle.Left, rectangle.Top, rectangle.Right, rectangle.Bottom, CropMode.Pixels); Crop crop = new Crop { DynamicParameter = cropLayer }; this.Image = crop.ProcessImage(this); } return this; }