public void BandC(int bValue, int cValue) { // I believe that the right way to do contrast and brightness together is always to apply // brightness first and then contrast. this.Reset(); imFactory.Brightness(bValue); imFactory.Contrast(cValue); }
/// <summary> /// Changes the contrast of the image. /// </summary> /// <param name="percentage">Contrast in percentage. From -100% to 100%.</param> /// <returns>The resulting image.</returns> public Image ChangeContrast(int percentage) { _editor.Load(_tempImage); _editor.Contrast(percentage); return(_editor.Image); }
/// <summary> /// /// </summary> /// <param name="folderPath">所有需切割图片所在文件夹路径</param> /// <param name="saveFolderPath">保存文件夹路径</param> public static void Qie(string folderPath, string saveFolderPath) { string[] filePaths = Directory.GetFiles(folderPath); for (int i = 0; i < filePaths.Length; i++) { //传入需切割图片 Bitmap img = new Bitmap(filePaths[i]); //克隆指定区域 Bitmap resultLeft = img.Clone(new Rectangle(0, 0, img.Width / 2, img.Height), img.PixelFormat); Bitmap resultRight = img.Clone(new Rectangle(img.Width / 2, 0, img.Width / 2, img.Height), img.PixelFormat); //用imageFactory增加对比度,删除背面透过来的文字 var imageFactoryLeft = new ImageFactory().Load(resultLeft); var imageFactoryRight = new ImageFactory().Load(resultRight); imageFactoryLeft.Contrast(80).Format(new ImageProcessor.Imaging.Formats.PngFormat()).Save(saveFolderPath + @"\" + i + @"left.png"); imageFactoryRight.Contrast(80).Format(new ImageProcessor.Imaging.Formats.PngFormat()).Save(saveFolderPath + @"\" + i + @"right.png"); //resultLeft.Save(SavePathLeft); resultLeft.Dispose(); //resultRight.Save(SavePathRight); resultRight.Dispose(); } }
/// <summary> /// Performs the Contrast effect from the ImageProcessor library. /// </summary> /// <param name="image">The image with which to apply the effect.</param> /// <param name="percentage">The amount of contrast as a percentage.</param> /// <returns>A new image with the Contrast effect applied.</returns> public Image Contrast(Image image, int percentage) { using var factory = new ImageFactory(); factory.Load(image); factory.Contrast(percentage); var result = factory.Image; return(new Bitmap(result)); }
public override void ProcessImage(ref ImageFactory imageFactory) { imageFactory.Resize(new Size(512, 512)); imageFactory.Pixelate(12); imageFactory.GaussianSharpen(20); imageFactory.Brightness(50); imageFactory.Contrast(50); imageFactory.Filter(ImageProcessor.Imaging.Filters.Photo.MatrixFilters.Invert); MemoryStream stream = new MemoryStream(); imageFactory.Save(stream); imageFactory.Reset(); imageFactory.Load(stream); imageFactory.Saturation(100); channel.SendMessage("PUNT"); }
public ImagePreviewResponse Preview(string imageId, string containerName, string imageFormat, int brightness, int contrast, int saturation, int sharpness, bool sepia, bool polaroid, bool greyscale) { var response = new ImagePreviewResponse(); //Create the id for the enhanced "preview" version of the source image string enhancedImageId = Guid.NewGuid().ToString(); var outputFormatString = string.Empty; ISupportedImageFormat outputFormatProcessorProperty = null; System.Drawing.Imaging.ImageFormat outputFormatSystemrawingFormat = null; #region Select image format, or send error switch (imageFormat) { case "jpg": outputFormatString = ".jpg"; outputFormatProcessorProperty = new JpegFormat { Quality = 90 }; outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case "gif": outputFormatString = ".gif"; outputFormatProcessorProperty = new GifFormat { }; outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Gif; break; case "png": outputFormatString = ".png"; outputFormatProcessorProperty = new PngFormat { }; outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Png; break; case "bmp": outputFormatString = ".bmp"; outputFormatProcessorProperty = new BitmapFormat { }; outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Bmp; break; case "tiff": outputFormatString = ".tiff"; outputFormatProcessorProperty = new TiffFormat { }; outputFormatSystemrawingFormat = System.Drawing.Imaging.ImageFormat.Tiff; break; default: return(new ImagePreviewResponse { isSuccess = false, ErrorMessage = "Please please use a supported file format: jpg, png, gif, bmp or tiff." }); } #endregion #region verify all input parameters, or send error if ( brightness < -100 || brightness > 100 || sharpness < -100 || sharpness > 100 || contrast < -100 || contrast > 100 || saturation < -100 || saturation > 100 ) { return(new ImagePreviewResponse { isSuccess = false, ErrorMessage = "Please pass in a value between -100 and 100 for all enhancement parameters" }); } #endregion //Build out response object response.ImageID = enhancedImageId; response.FileName = enhancedImageId + outputFormatString; response.SourceFile = imageId + outputFormatString; #region Connect to Intermediary Storage // Credentials are from centralized CoreServiceSettings StorageCredentials storageCredentials = new StorageCredentials(CoreServices.PlatformSettings.Storage.IntermediaryName, CoreServices.PlatformSettings.Storage.IntermediaryKey); var storageAccount = new CloudStorageAccount(storageCredentials, false); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); #endregion try { //Pull down the source image as MemoryStream from Blob storage and apply image enhancement properties using (MemoryStream sourceStream = Common.GetAssetFromIntermediaryStorage(response.SourceFile, containerName, blobClient)) { #region Image Processor & Storage 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; imageFactory.Load(sourceStream); if (brightness != 0) { imageFactory.Brightness(brightness); } if (contrast != 0) { imageFactory.Contrast(contrast); } if (saturation != 0) { imageFactory.Saturation(saturation); } //Sharpness if (sharpness != 0) { imageFactory.GaussianSharpen(sharpness); } //Filters if (sepia == true) { imageFactory.Filter(MatrixFilters.Sepia); } if (polaroid == true) { imageFactory.Filter(MatrixFilters.Polaroid); } if (greyscale == true) { imageFactory.Filter(MatrixFilters.GreyScale); } imageFactory.Save(outStream); } //Store each image size to BLOB STORAGE --------------------------------- #region BLOB STORAGE //Creat/Connect to the Blob Container //blobClient.GetContainerReference(containerName).CreateIfNotExists(BlobContainerPublicAccessType.Blob); //<-- Create and make public CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName); //Get reference to the picture blob or create if not exists. CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(response.FileName); //Save to storage //Convert final BMP to byteArray Byte[] finalByteArray; finalByteArray = outStream.ToArray(); //Store the enhanced "preview" into the same container as the soure blockBlob.UploadFromByteArray(finalByteArray, 0, finalByteArray.Length); #endregion } #endregion } } catch (Exception e) { return(new ImagePreviewResponse { isSuccess = false, ErrorMessage = e.Message }); } //Marke as successful and return the new ImageID and FileName back to the client for previewing: response.isSuccess = true; return(response); }
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 } }
private void ContrastBtn_Click(object sender, EventArgs e) { imageFactory.Contrast(contrastBar.Value); pictureBox.Image = imageFactory.Image; }
public IImageTransformer Contrast(int percentage) { _image.Contrast(percentage); return(this); }
public static void Process(ref byte[] buffer, Dictionary <string, double> edits) { using (var inputStream = new MemoryStream(buffer)) { using (var outputStream = new MemoryStream()) { using (var factory = new ImageFactory()) { factory.Load(inputStream); foreach (var edit in edits) { switch (edit.Key) { case "Alpha": { factory.Alpha((int)edit.Value); break; } case "Contrast": { factory.Contrast((int)edit.Value); break; } case "Exposure": { factory.Brightness((int)edit.Value); break; } case "Flip": { var flipVertical = edit.Value == 1; factory.Flip(flipVertical); break; } case "Pixelate": { factory.Pixelate((int)edit.Value); break; } case "Quality": { factory.Quality((int)edit.Value); break; } case "Rotate": { factory.Rotate((int)edit.Value); break; } case "Rounded": { factory.RoundedCorners((int)edit.Value); break; } case "Saturation": { factory.Saturation((int)edit.Value); break; } } } factory.Save(outputStream); var length = (int)outputStream.Length; buffer = new byte[length]; outputStream.Read(buffer, 0, length); } } } }
public override void Apply(ImageFactory fs) { fs = fs.Contrast(percentage); }
private static void ApplyFilterSetting(ImageFactory imageToAdjust, string setting, string value) { switch (setting) { case "brightness": imageToAdjust.Brightness(int.Parse(value)); break; case "contrast": imageToAdjust.Contrast(int.Parse(value)); break; case "filter": switch (value) { case "gotham": imageToAdjust.Filter(MatrixFilters.Gotham); break; case "invert": imageToAdjust.Filter(MatrixFilters.Invert); break; case "polaroid": imageToAdjust.Filter(MatrixFilters.Polaroid); break; case "blackwhite": imageToAdjust.Filter(MatrixFilters.BlackWhite); break; case "greyscale": imageToAdjust.Filter(MatrixFilters.GreyScale); break; case "lomograph": imageToAdjust.Filter(MatrixFilters.Lomograph); break; case "sepia": imageToAdjust.Filter(MatrixFilters.Sepia); break; case "comic": imageToAdjust.Filter(MatrixFilters.Comic); break; case "hisatch": imageToAdjust.Filter(MatrixFilters.HiSatch); break; case "losatch": imageToAdjust.Filter(MatrixFilters.LoSatch); break; } break; case "flip": imageToAdjust.Flip(flipVertically: value == "vertical", flipBoth: value == "both"); break; case "rotate": imageToAdjust.Rotate(int.Parse(value)); break; } }