private long Test_LosslessCompress(string fileName, bool resultIsSmaller) { FileInfo tempFile = CreateTemporaryFile(fileName); try { IImageOptimizer optimizer = CreateImageOptimizer(); Assert.IsNotNull(optimizer); long before = tempFile.Length; optimizer.LosslessCompress(tempFile); long after = tempFile.Length; if (resultIsSmaller) { Assert.IsTrue(after < before, "{0} is not smaller than {1}", after, before); } else { Assert.AreEqual(before, after); } return(after); } finally { tempFile.Delete(); } }
protected void Test_LosslessCompress_InvalidArguments() { IImageOptimizer optimizer = CreateImageOptimizer(); Assert.IsNotNull(optimizer); ExceptionAssert.Throws <ArgumentNullException>(delegate() { optimizer.LosslessCompress((FileInfo)null); }); ExceptionAssert.Throws <ArgumentNullException>(delegate() { optimizer.LosslessCompress((string)null); }); ExceptionAssert.Throws <ArgumentException>(delegate() { optimizer.LosslessCompress(""); }); ExceptionAssert.Throws <ArgumentException>(delegate() { optimizer.LosslessCompress(Files.Missing); }); }
/// <summary> /// Removes an optimizer from the factory /// </summary> /// <param name="optimizer">The optimizer to remove.</param> public void Remove(IImageOptimizer optimizer) { lock (_Lock) { _Optimizers.Remove(optimizer); } }
/// <summary> /// Adds an optimizer to the factory /// </summary> /// <param name="optimizer">The optimizer to add.</param> public void Add(IImageOptimizer optimizer) { lock (_Lock) { _Optimizers.Add(optimizer); } }
public BusinessUnitsController(IBusinessUnitService businessUnitService, IUserService userService, IImageOptimizer optimizer) { this.businessUnitService = businessUnitService; this.userService = userService; this.optimizer = optimizer; }
public LogbooksController(ILogbookService logbookService, IUserService userService, IImageOptimizer optimizer) { this.logbookService = logbookService; this.userService = userService; this.optimizer = optimizer; }
public UsersController(IUserService userService, IViewModelMapper <ApplicationUser, UserViewModel> userMapper, IImageOptimizer optimizer, IViewModelMapper <Review, ReviewViewModel> reviewMapper) { this.userService = userService ?? throw new ArgumentNullException(nameof(userService)); this.userMapper = userMapper ?? throw new ArgumentNullException(nameof(userMapper)); this.optimizer = optimizer ?? throw new ArgumentNullException(nameof(optimizer)); this.reviewMapper = reviewMapper ?? throw new ArgumentNullException(nameof(reviewMapper)); }
private bool DoCompress(FileInfo file) { IImageOptimizer optimizer = GetOptimizer(file); if (optimizer == null) { return(false); } optimizer.OptimalCompression = OptimalCompression; return(optimizer.Compress(file)); }
public ActorsController(IActorService actorService, IMovieService movieService, IImageOptimizer optimizer, IViewModelMapper <Actor, ActorViewModel> actorMapper, IViewModelMapper <Movie, MovieViewModel> movieMapper) { this.actorService = actorService ?? throw new ArgumentNullException(nameof(actorService)); this.movieService = movieService ?? throw new ArgumentNullException(nameof(movieService)); this.optimizer = optimizer ?? throw new ArgumentNullException(nameof(optimizer)); this.actorMapper = actorMapper ?? throw new ArgumentNullException(nameof(actorMapper)); this.movieMapper = movieMapper ?? throw new ArgumentNullException(nameof(movieMapper)); }
public void Process(GetMediaStreamPipelineArgs args) { Sitecore.Diagnostics.Assert.ArgumentNotNull((object)args, "args"); if (args.Options.Thumbnail) { return; } MediaStream outputStream = args.OutputStream; if (outputStream == null) { return; } if (!outputStream.AllowMemoryLoading) { Tracer.Error((object)"Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", (object)outputStream.MediaItem.Path); } else { if (!args.MediaData.MimeType.StartsWith("image/", StringComparison.Ordinal)) { return; } string str = args.MediaData.Extension.ToLower(); IImageOptimizer imageOptimizer = (IImageOptimizer)null; if (str.Equals("png")) { imageOptimizer = (IImageOptimizer) new PngOptimizer(outputStream.Stream); } if (str.Equals("jpg") || str.Equals("jpeg")) { imageOptimizer = (IImageOptimizer) new JpegOptimizer(outputStream.Stream); } if (imageOptimizer == null) { return; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); IOptimizerResult optimizerResult = imageOptimizer.Optimize(); stopwatch.Stop(); if (optimizerResult.Success) { outputStream.Stream.Close(); Sitecore.Diagnostics.Log.Info(StringExtensions.FormatWith("HealthIS: optimized {0}.{1} ({2} bytes) - saved {3} bytes / {4:p}. Optimized in {5}ms.", (object)args.OutputStream.MediaItem.MediaPath, (object)args.OutputStream.MediaItem.Extension, (object)optimizerResult.SizeAfter, (object)(optimizerResult.SizeBefore - optimizerResult.SizeAfter), (object)(float)(1.0 - (double)optimizerResult.SizeAfter / (double)optimizerResult.SizeBefore), (object)stopwatch.ElapsedMilliseconds), (object)this); args.OutputStream = new MediaStream(optimizerResult.CreateResultStream(), outputStream.Extension, outputStream.MediaItem); } else { Sitecore.Diagnostics.Log.Error(StringExtensions.FormatWith("HealthIS: unable to optimize {0} because {1}", (object)args.OutputStream.MediaItem.Name, (object)optimizerResult.ErrorMessage), (object)this); } } }
private void DoCompress(FileInfo file) { IImageOptimizer optimizer = GetOptimizer(file); if (optimizer == null) { return; } optimizer.OptimalCompression = OptimalCompression; optimizer.Compress(file); }
public CreateController( UserManager <User> userManager, SignInManager <User> signInManager, IEmailSender emailSender, ILogger <CreateController> logger, IImageOptimizer optimizer) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _logger = logger; this.optimizer = optimizer; }
/// <summary> /// Performs compression on the specified stream. With some formats the image will be decoded /// and encoded and this will result in a small quality reduction. If the new size is not /// smaller the stream won't be overwritten. /// </summary> /// <param name="stream">The stream of the image to compress.</param> /// <returns>True when the image could be compressed otherwise false.</returns> public bool Compress(Stream stream) { ImageOptimizerHelper.CheckStream(stream); IImageOptimizer optimizer = GetOptimizer(stream); if (optimizer == null) { return(false); } optimizer.OptimalCompression = OptimalCompression; return(optimizer.Compress(stream)); }
public MoviesController(IMovieService movieService, IViewModelMapper <Movie, MovieViewModel> movieViewMapper, IActorService actorService, IViewModelMapper <Actor, ActorViewModel> actorViewMapper, IImageOptimizer optimizer, SignInManager <ApplicationUser> signInManager) { this.optimizer = optimizer; this.movieService = movieService ?? throw new ArgumentNullException(nameof(movieService)); this.movieViewMapper = movieViewMapper ?? throw new ArgumentNullException(nameof(movieViewMapper)); this.actorService = actorService ?? throw new ArgumentNullException(nameof(actorService)); this.actorViewMapper = actorViewMapper ?? throw new ArgumentNullException(nameof(actorViewMapper)); this.signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager)); }
public NotesController(IImageOptimizer optimizer, IUserService userService, INoteService noteService, ILogbookService logbookService, IMemoryCache cache, IUserServiceWrapper wrapper) { this.optimizer = optimizer; this.noteService = noteService; this.userService = userService; this.logbookService = logbookService; this.cache = cache; this.wrapper = wrapper; }
/// <summary> /// Get an optimizer from the factory /// </summary> /// <param name="name">The name of the optimizer.</param> public IImageOptimizer GetByName(string name) { lock (_Lock) { IImageOptimizer optimizer = _Optimizers.FirstOrDefault(o => o.Name.ToLower() == name.ToLower()); if (optimizer != null) { return((IImageOptimizer)optimizer.Clone()); } else { return(null); } } }
/// <summary> /// Get an optimizer from the factory /// </summary> /// <param name="extension">The extension of the file that the optimzer needs to support.</param> public IImageOptimizer GetByExtension(string extension) { lock (_Lock) { IImageOptimizer optimizer = _Optimizers.FirstOrDefault(o => o.Supports(extension)); if (optimizer != null) { return((IImageOptimizer)optimizer.Clone()); } else { return(null); } } }
public UploadController(ILifetimeScope container) { _logger = container.Resolve <ILogger <UploadController> >(); _imageOptimizer = container.Resolve <IImageOptimizer>(); IHostingEnvironment hostingEnv = container.Resolve <IHostingEnvironment>(); try { siteAssetPath = Path.Combine(hostingEnv.WebRootPath, Globals.SiteAssetsPath.Replace("~/", "").Replace("/", @"\")); localImageUploadPath = Path.Combine(siteAssetPath, Globals.ImagesFolder); } catch { throw; } }
protected void Test_LosslessCompress_InvalidFile(string fileName) { FileInfo tempFile = CreateTemporaryFile(fileName); try { ExceptionAssert.Throws <MagickCorruptImageErrorException>(delegate() { IImageOptimizer optimizer = CreateImageOptimizer(); Assert.IsNotNull(optimizer); optimizer.LosslessCompress(tempFile); }); } finally { tempFile.Delete(); } }
public static bool Optimize(this IImageOptimizer imageOptimizer, string inputFilePath, string outputFilePath, ImageOptimizationMode optimizationMode) { using (MemoryStream ms = new MemoryStream()) { using (FileStream inputStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read)) inputStream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); bool success = imageOptimizer.Optimize(ms, optimizationMode); if (success) { ms.Seek(0, SeekOrigin.Begin); using (FileStream outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write)) ms.CopyTo(outputStream); } return(success); } }
public UploadController(ILogger <UploadController> logger, IImageOptimizer imageOptimizer, IWebHostEnvironment hostEnvironment) { _logger = logger; _imageOptimizer = imageOptimizer; try { var siteAssetPath = Path.Combine(hostEnvironment.WebRootPath, Globals.SiteAssetsPath.Replace("~/", "").Replace("/", @"\")); _localImageUploadPath = Path.Combine(siteAssetPath, Globals.ImagesFolder); _localDocumentUploadPath = Path.Combine(siteAssetPath, Globals.DocumentsFolder); if (!Directory.Exists(_localImageUploadPath)) { Directory.CreateDirectory(_localImageUploadPath); } } catch (Exception ex) { _logger.LogError(string.Format("Error occured while getting images"), ex); } }
public static void Save(this IImage image, Stream stream, IFileFormat imageFormat, IImageEncoderOptions encoderOptions) { IImageEncoder encoder = ImageCodec.FromFileFormat(imageFormat); if (encoder is null) { throw new UnsupportedFileFormatException(); } encoder.Encode(image, stream, encoderOptions); if (stream.CanSeek && encoderOptions.OptimizationMode != ImageOptimizationMode.None) { IImageOptimizer imageOptimizer = ImageOptimizer.FromImageFormat(imageFormat); if (!(imageOptimizer is null)) { stream.Seek(0, SeekOrigin.Begin); imageOptimizer.Optimize(stream, encoderOptions.OptimizationMode); } } }
/// <summary> /// Get an optimizer from the factory /// </summary> /// <param name="optimizer">The name of the optimizer.</param> /// <param name="sourcePath">The path of the file to optimize.</param> /// <param name="outputPath">The output path for the optimized image.</param> public ImageOptimizerResult Optimize(string optimizer, FilePath sourcePath, FilePath outputPath) { //Get Optimizer IImageOptimizer optim = null; if (!String.IsNullOrEmpty(optimizer)) { optim = this.GetByName(optimizer); } if (optim == null) { optim = this.GetByPath(sourcePath); } //Get Result ImageOptimizerResult result = null; if (optim != null) { try { //Optimize IFile file = _FileSystem.GetFile(sourcePath); if ((optim.FileSize == 0) || (file.Length < optim.FileSize)) { result = optim.Optimize(sourcePath); //Check Sizes if (result.SizeBefore == 0) { result.SizeBefore = file.Length; result.SizeAfter = result.SizeBefore; } //Replace File if (result.SizeAfter != result.SizeBefore) { Directory.CreateDirectory(outputPath.GetDirectory().FullPath); using (WebClient client = new WebClient()) { client.DownloadFile(result.DownloadUrl, outputPath.FullPath); } //Date Modified result.ModifiedDate = new FileInfo(file.Path.FullPath).LastWriteTime; } else { //Skipped result = new ImageOptimizerResult(optim.Name, sourcePath, "Matching FileSize"); } } else { //Skipped result = new ImageOptimizerResult(optim.Name, sourcePath, "Invalid FileSize"); } } catch (Exception ex) { //Error result = new ImageOptimizerResult(optim.Name, sourcePath, ex.Message); } } else { //Unsupported File result = new ImageOptimizerResult(optimizer, sourcePath, "Unsupported File"); } return(result); }
public void Process(GetMediaStreamPipelineArgs args) { Assert.ArgumentNotNull(args, "args"); if (args.Options.Thumbnail) { return; } MediaStream outputStream = args.OutputStream; if (outputStream == null) { return; } if (!outputStream.AllowMemoryLoading) { Tracer.Error("Could not resize image as it was larger than the maximum size allowed for memory processing. Media item: {0}", outputStream.MediaItem.Path); return; } string mimeType = args.MediaData.MimeType; if (!mimeType.StartsWith("image/", StringComparison.Ordinal)) { return; } string extension = args.MediaData.Extension; IImageOptimizer optimizer = null; if (extension.Equals("png")) { optimizer = new PngOptimizer(outputStream.Stream); } if (extension.Equals("jpg") || extension.Equals("jpeg")) { optimizer = new JpegOptimizer(outputStream.Stream); } if (optimizer == null) { return; } var sw = new Stopwatch(); sw.Start(); var result = optimizer.Optimize(); sw.Stop(); if (result.Success) { outputStream.Stream.Close(); Log.Info("Dianoga: optimized {0}.{1} ({2} bytes) - saved {3} bytes / {4:p}. Optimized in {5}ms.".FormatWith(args.OutputStream.MediaItem.MediaPath, args.OutputStream.MediaItem.Extension, result.SizeAfter, result.SizeBefore - result.SizeAfter, 1 - ((result.SizeAfter / (float)result.SizeBefore)), sw.ElapsedMilliseconds), this); args.OutputStream = new MediaStream(result.CreateResultStream(), outputStream.Extension, outputStream.MediaItem); } else { Log.Error("Dianoga: unable to optimize {0} because {1}".FormatWith(args.OutputStream.MediaItem.Name, result.ErrorMessage), this); } }
public static async Task <ImageRecord> GetOrSaveRowAsync(CloudTable imageTable, CloudBlobClient imagesBlobClient, IImageOptimizer optimizer, string siteId, string imageUrl, string optimizedImageName) { System.Diagnostics.Trace.TraceInformation($"Checking for existing row using `{imageTable.Name}` table for `{siteId}` site image `{imageUrl}`."); var existingRecord = await GetRowIfExistsAsync(imageTable, siteId, imageUrl).ConfigureAwait(false); if (existingRecord != null) { System.Diagnostics.Trace.TraceInformation($"Found existing row using `{imageTable.Name}` table for `{siteId}` site image `{imageUrl}`."); return(existingRecord); } System.Diagnostics.Trace.TraceInformation($"No existing row found using `{imageTable.Name}` table for `{siteId}` site image `{imageUrl}`."); System.Diagnostics.Trace.TraceInformation($"Getting bytes for `{siteId}` site image `{imageUrl}`."); var siteImagesContainer = imagesBlobClient.GetContainerReference(siteId); await siteImagesContainer.CreateIfNotExistsAsync().ConfigureAwait(false); // TODO: could be optimized to not download bytes when an optimization is not required var imageBytes = await GetOrSaveImageBytesAsync(siteImagesContainer, siteId, imageUrl, optimizedImageName).ConfigureAwait(false); if (imageBytes == null) { System.Diagnostics.Trace.TraceInformation($"Unable to get bytes for `{siteId}` site image `{imageUrl}`."); return(null); } var optimizedBlob = await GetOrSaveOptimizedBlobAsync(siteImagesContainer, optimizer, siteId, imageUrl, optimizedImageName, imageBytes.Item2).ConfigureAwait(false); ImageRecord newRecord = new ImageRecord() { SiteId = siteId, ImageUrl = imageUrl, ImageLocalCopyUrl = imageBytes.Item1.Uri.AbsoluteUri, OptimizedImageUrl = optimizedBlob.Uri.AbsoluteUri, ImageName = optimizedImageName }; System.Diagnostics.Trace.TraceInformation($"Creating image record for `{siteId}` site image `{imageUrl}` original copy `{newRecord.ImageLocalCopyUrl}` optimized copy `{newRecord.OptimizedImageUrl}`."); await imageTable.ExecuteAsync(TableOperation.Insert(newRecord)).ConfigureAwait(false); System.Diagnostics.Trace.TraceInformation($"Created image record for `{siteId}` site image `{imageUrl}` original copy `{newRecord.ImageLocalCopyUrl}` optimized copy `{newRecord.OptimizedImageUrl}`."); return(newRecord); }
public PngHelper(IImageOptimizer optimizer) { _optimalCompression = optimizer.OptimalCompression; }
/// <summary> /// Initializes a new instance of the <see cref="ImageManager"/> class. /// </summary> /// <param name="imageTable"> /// The <see cref="CloudTable" /> used to store relationships between /// original and optimized images /// </param> /// <param name="imageBlobClient"> /// The <see cref="CloudBlobClient" /> used to store the original and /// optimized images /// </param> /// <param name="optimizer"> /// The image optimizer used to optimize images /// </param> public ImageManager(CloudTable imageTable, CloudBlobClient imageBlobClient, IImageOptimizer optimizer) { this.ImageTable = imageTable; this.ImageBlobClient = imageBlobClient; this.Optimizer = optimizer; }
/// <summary> /// Creates an image manager along with storage dependencies, if needed /// </summary> /// <param name="tableStorageAccount"> /// The storage account used to save original and optimized images /// </param> /// <param name="imageTableName"> /// The name of the table storing the relationship between original /// and optimized images /// </param> /// <param name="optimizer"> /// The image optimizer used to optimize images /// </param> /// <returns></returns> public static async Task <ImageManager> CreateAsync(CloudStorageAccount tableStorageAccount, Microsoft.Azure.Storage.CloudStorageAccount blobStorageAccount, string imageTableName, IImageOptimizer optimizer) { var tableClient = tableStorageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference(imageTableName); await table.CreateIfNotExistsAsync().ConfigureAwait(false); return(new ImageManager(table, blobStorageAccount.CreateCloudBlobClient(), optimizer)); }
protected static async Task <CloudBlockBlob> GetOrSaveOptimizedBlobAsync(CloudBlobContainer siteImagesContainer, IImageOptimizer krakenClient, string siteId, string imageUrl, string optimizedImageName, byte[] imageBytes) { System.Diagnostics.Trace.TraceInformation($"Checking for optimized bytes for `{siteId}` site image `{imageUrl}`."); var optimizedBlob = siteImagesContainer.GetBlockBlobReference($"{OptimizedFolderPrefix}{optimizedImageName}"); bool optimizeExists = await optimizedBlob.ExistsAsync().ConfigureAwait(false); if (optimizeExists) { System.Diagnostics.Trace.TraceInformation($"Optimized bytes exist for `{siteId}` site image `{imageUrl}`."); await optimizedBlob.FetchAttributesAsync().ConfigureAwait(false); System.Diagnostics.Trace.TraceInformation($"Optimized bytes exist for `{siteId}` site image `{imageUrl}` with size {optimizedBlob.Properties.Length:D}."); optimizeExists = optimizedBlob.Properties.Length > 0; } if (!optimizeExists) { System.Diagnostics.Trace.TraceInformation($"Optimized bytes do not exist for `{siteId}` site image `{imageUrl}`."); System.Diagnostics.Trace.TraceInformation($"Optimizing `{siteId}` site image `{imageUrl}`."); var optimizedBytes = await krakenClient.OptimizeBytesAsync(imageBytes, optimizedImageName).ConfigureAwait(false); System.Diagnostics.Trace.TraceInformation($"Saving optimized bytes for `{siteId}` site image `{imageUrl}`."); await optimizedBlob.UploadFromByteArrayAsync(optimizedBytes, 0, optimizedBytes.Length).ConfigureAwait(false); System.Diagnostics.Trace.TraceInformation($"Saved optimized bytes for `{siteId}` site image `{imageUrl}`."); } else { System.Diagnostics.Trace.TraceInformation($"Using existing optimized bytes for `{siteId}` site image `{imageUrl}`."); } return(optimizedBlob); }