public void ShouldThrowExceptionWhenFileIsEmpty() { var optimizer = new ImageOptimizer(); using (TemporaryFile file = new TemporaryFile("empty")) { ExceptionAssert.Throws <MagickMissingDelegateErrorException>(() => { optimizer.Compress(file); }); } }
public void ShouldThrowExceptionWhenStreamIsUnsupportedFormat() { var optimizer = new ImageOptimizer(); using (FileStream fileStream = OpenStream(Files.InvitationTIF)) { ExceptionAssert.Throws <MagickCorruptImageErrorException>(() => { optimizer.Compress(fileStream); }, "Invalid format"); } }
public void ShouldNotThrowExceptionWhenIgnoringUnsupportedStream() { var optimizer = new ImageOptimizer { IgnoreUnsupportedFormats = true }; using (FileStream fileStream = OpenFile(Files.InvitationTIF)) { var compressionSuccess = optimizer.Compress(fileStream); Assert.IsFalse(compressionSuccess); } }
public void ShouldThrowExceptionWhenStreamCannotSeek() { var optimizer = new ImageOptimizer(); using (TestStream stream = new TestStream(true, true, false)) { ExceptionAssert.ThrowsArgumentException("stream", () => { optimizer.Compress(stream); }); } }
public void ShouldThrowExceptionWhenStreamCannotRead() { var optimizer = new ImageOptimizer(); using (var stream = new TestStream(false, true, true)) { Assert.Throws <ArgumentException>("stream", () => { optimizer.Compress(stream); }); } }
private void compressImage(string path) { var file = new FileInfo(path); Console.WriteLine("Bytes before: " + file.Length); var optimizer = new ImageOptimizer(); optimizer.Compress(file); file.Refresh(); Console.WriteLine("Bytes after: " + file.Length); }
private static CompressionResult[] OptimizeImages(Repository repo, string localPath, string[] imagePaths, ILogger logger, bool aggressiveCompression) { var optimizedImages = new List <CompressionResult>(); ImageOptimizer imageOptimizer = new ImageOptimizer { OptimalCompression = true, IgnoreUnsupportedFormats = true, }; Parallel.ForEach(imagePaths, image => { try { var tokenSource = new CancellationTokenSource(); var task = Task.Factory.StartNew( () => { Console.WriteLine(image); FileInfo file = new FileInfo(image); double before = file.Length; if (aggressiveCompression ? imageOptimizer.Compress(file) : imageOptimizer.LosslessCompress(file)) { optimizedImages.Add(new CompressionResult { Title = image.Substring(localPath.Length), OriginalPath = image, SizeBefore = before / 1024d, SizeAfter = file.Length / 1024d, }); } }, tokenSource.Token); // returns true if the Task completed execution within the allotted time; otherwise, false. // Cancel and continue with the rest if (task.Wait(600 * 1000) == false) { logger.LogInformation("Timeout processing {Image}", image); tokenSource.Cancel(); } } catch (Exception ex) { Console.WriteLine(ex.Message); logger.LogError(ex, $"Compression issue with {image}"); } }); logger.LogInformation("Compressed {NumImages}", optimizedImages.Count); return(optimizedImages.ToArray()); }
public static void Optimize(this ImageOptimizer imageOptimizer, string file, [FromServices] ILogger <ImageOptimizer> logger) { if (imageOptimizer.IsSupported(file)) { try { imageOptimizer.Compress(file); } catch (Exception ex) { logger.LogWarning(ex.Message); } } }
public void ShouldThrowExceptionWhenStreamIsUnsupportedFormat() { var optimizer = new ImageOptimizer(); using (var fileStream = OpenStream(Files.InvitationTIF)) { var exception = Assert.Throws <MagickCorruptImageErrorException>(() => { optimizer.Compress(fileStream); }); Assert.Contains("Invalid format", exception.Message); } }
public async Task <ActionResult> FileUpload() { string filePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, _filePath); if (!System.IO.Directory.Exists(filePath)) { System.IO.Directory.CreateDirectory(filePath); } var file = Request.Form.Files.FirstOrDefault(); if (file == null) { throw new Abp.UI.UserFriendlyException(417, "没有图片"); } string fileType = file.FileName.Split(".").LastOrDefault(); string[] fileTypeArr = new string[] { "jpg", "gif", "png", "jpeg" }; if (string.IsNullOrEmpty(fileType) || !fileTypeArr.Contains(fileType.ToLower())) { throw new Abp.UI.UserFriendlyException(415, "非图片文件"); } string fileName = DateTime.Now.ToString("yyyyMMddHHmm_") + file.FileName; string fullFilePath = System.IO.Path.Combine(filePath, fileName); using (System.IO.FileStream fs = System.IO.File.Create(fullFilePath)) { await file.CopyToAsync(fs); await fs.FlushAsync(); } var savedFile = new System.IO.FileInfo(fullFilePath); var optimizer = new ImageOptimizer(); optimizer.Compress(savedFile); savedFile.Refresh(); return(Json(new { StatusCode = 200, Info = "图片上传成功!", Data = new { url = string.Format("{0}{1}/{2}{3}", "Http://", Request.Host, _filePath, fileName), name = fileName, } })); }
public ActionResult Details(IFormFile image) { var s = _hostingEnvironment.WebRootPath + "/uploads/" + "637271913469540954Green-Embroidered-Worked-Fabric-3401-5.jpeg"; var file = new FileInfo(s); var before = file.Length; var optimizer = new ImageOptimizer(); optimizer.Compress(file); file.Refresh(); var after = file.Length; return(Json(new { before, after, file.Attributes })); }
private static void OptimizeImg(string imgLocation) { try { var snakewareLogo = new FileInfo(imgLocation); var optimizer = new ImageOptimizer { OptimalCompression = true }; optimizer.Compress(snakewareLogo); snakewareLogo.Refresh(); } catch (Exception) { // ignored } }
public bool CompressImage(string filePath, bool lossless = true) { var fullPath = GetBasePath(filePath); var file = new FileInfo(fullPath); var optimizer = new ImageOptimizer(); bool result; if (lossless) { result = optimizer.LosslessCompress(file); file.Refresh(); return(result); } result = optimizer.Compress(file); return(result); }
private static void ProcessImage(MagickImage image, int maxImageDimension, string filePath) { if (image.Width > image.Height) { image.Resize(maxImageDimension, 0); } else { image.Resize(0, maxImageDimension); } image.Write(filePath); ImageOptimizer optimizer = new ImageOptimizer(); optimizer.OptimalCompression = true; optimizer.Compress(filePath); }
public Photo CreatePhoto(IFormFile image) { Photo photo = new Photo() { Id = Guid.NewGuid().ToString() }; using (var stream = image.OpenReadStream()) { if (FileHelper.IsValidFileExtensionAndSignature(image.FileName, stream, _permittedExtensions)) { string path = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images"); if (!Directory.Exists(path)) { DirectoryInfo di = Directory.CreateDirectory(path); } string fileName = photo.Id + Path.GetExtension(image.FileName); string fullPath = Path.Combine(path, fileName); using (var fileStream = new FileStream(fullPath, FileMode.Create)) { using (var binaryWriter = new BinaryWriter(fileStream)) { using (var binaryReader = new BinaryReader(image.OpenReadStream())) { binaryWriter.Write(binaryReader.ReadBytes((int)image.Length)); } } } HttpContextAccessor httpContextAccessor = new HttpContextAccessor(); var file = new FileInfo(fullPath); var optimizer = new ImageOptimizer(); optimizer.Compress(file); file.Refresh(); photo.Url = "https://" + httpContextAccessor.HttpContext.Request.Host.Value + @"\images\" + fileName; photo.FileName = fileName; photo.Path = fullPath; photo.Size = image.Length; } } return(photo); }
private static void OnImageProcessing(Options o, string destFolder, bool copy, string fileName) { var source = Path.Combine(o.SourceFolder, fileName); var filePath = Path.Combine(destFolder, fileName); CopyFile(copy, source, filePath); var file = new FileInfo(filePath); var optimizer = new ImageOptimizer(); optimizer.Compress(file); MagickImage image = new MagickImage(file); image.Resize(new Percentage(o.Percentage)); image.Write(file); }
public string CompressInPlace(string imagePath) { MagickFormat format = MagickFormat.Jpeg; string targetPath = $"{imagePath}.{format}"; var fileInfo = new FileInfo(imagePath); var optimizer = new ImageOptimizer(); ChangeFileFormat(imagePath, targetPath, format); if (losless) { optimizer.LosslessCompress(targetPath); } else { optimizer.Compress(fileInfo); } return(targetPath); }
public static void OptimizeImage(string path) { FileInfo fileInfo = new FileInfo(path); if (!fileInfo.Exists) { return; } ImageOptimizer optimizer = new ImageOptimizer(); optimizer.Compress(fileInfo); fileInfo.Refresh(); using (MagickImage mImage = new MagickImage(fileInfo)) { mImage.Resize(new MagickGeometry(1920, 1080)); mImage.Write(fileInfo); } fileInfo.Refresh(); }
protected void Test_Compress_Smaller(string fileName) { FileInfo tempFile = CreateTemporaryFile(fileName); try { ImageOptimizer optimizer = new ImageOptimizer(); Assert.IsNotNull(optimizer); long before = tempFile.Length; optimizer.Compress(tempFile); long after = tempFile.Length; Assert.IsTrue(after < before, "{0} is not smaller than {1}", after, before); } finally { tempFile.Delete(); } }
public void Compress_UTF8PathName_CanCompressFile() { string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + "爱"); Directory.CreateDirectory(tempDir); string tempFile = Path.Combine(tempDir, "ImageMagick.jpg"); File.Copy(Files.ImageMagickJPG, tempFile); try { var optimizer = new ImageOptimizer(); optimizer.Compress(tempFile); } finally { File.Delete(tempFile); Directory.Delete(tempDir); } }
private static CompressionResult[] OptimizeImages(Repository repo, string localPath, string[] imagePaths, ILogger logger, bool aggressiveCompression) { var optimizedImages = new List <CompressionResult>(); ImageOptimizer imageOptimizer = new ImageOptimizer { OptimalCompression = true, IgnoreUnsupportedFormats = true, }; Parallel.ForEach(imagePaths, image => { try { Console.WriteLine(image); FileInfo file = new FileInfo(image); double before = file.Length; if (aggressiveCompression ? imageOptimizer.Compress(file) : imageOptimizer.LosslessCompress(file)) { optimizedImages.Add(new CompressionResult { Title = image.Substring(localPath.Length), OriginalPath = image, SizeBefore = before / 1024d, SizeAfter = file.Length / 1024d, }); } } catch (Exception ex) { Console.WriteLine(ex.Message); logger.LogError(ex, $"Compression issue with {image}"); } }); logger.LogInformation("Compressed {NumImages}", optimizedImages.Count); return(optimizedImages.ToArray()); }
/// <summary> /// Processes a request to determine if it matches a known image, otherwise it will generate it. /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task Invoke(HttpContext context) { var path = context.Request.Path; var extension = Path.GetExtension(path.Value); if (!GenericHelpers.IsGetOrHeadMethod(context.Request.Method)) { this.logger.LogRequestMethodNotSupported(context.Request.Method); } else if (!GenericHelpers.IsRequestFileTypeSupported( extension, this.options.OutputFormats.SelectMany( x => x.FileEndings).ToArray() ) ) { this.logger.LogRequestFileTypeNotSupported(extension); } else if (!GenericHelpers.TryMatchPath(path, this.options.TargetFolder)) { this.logger.LogPathMismatch(path); } else { // get the image location on disk var imagePath = Path.Combine( this.env.WebRootPath, path.Value .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar) ); if (!File.Exists(imagePath)) { this.logger.LogProcessingImage(path.Value); var size = Path.GetFileNameWithoutExtension(path.Value).ToLower(); var filename = Directory.GetParent(path.Value).Name; // var imageSourcePath = Path.Combine( // $"{this.env.ContentRootPath}{this.options.SourceFolder}", // $"{filename}{extension}" // ); FileInfo sourceImageFile; var sourceImageFolder = new DirectoryInfo(Path.Combine( $"{this.env.ContentRootPath}{this.options.SourceFolder}" )); var sourceImageFiles = sourceImageFolder.GetFiles($"{filename}.*"); if (sourceImageFiles == null || sourceImageFiles.Length == 0) { // Image source not found! // Hand over to the next middleware and return. this.logger.LogSourceImageNotFound($"{filename}.*"); await this.next(context); return; } else { if (sourceImageFiles.Length > 1) { this.logger.LogWarning( $"Found multiple source images, take first one: {sourceImageFiles[0].Name}" ); } sourceImageFile = sourceImageFiles[0]; } var targetDir = Path.Combine( this.env.WebRootPath, this.options.TargetFolder .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar), filename ); if (!Directory.Exists(targetDir)) { this.logger.LogInformation($"Create Directory: \"{targetDir}\""); Directory.CreateDirectory(targetDir); } var sizeSetting = this.options.Sizes.FirstOrDefault( x => (x.Name ?? x.Width.ToString()).ToLower() == size ); if (sizeSetting == null) { // Not supported size! // Hand over to the next middleware and return. this.logger.LogSizeNotSupported(size); await this.next(context); return; } var sourceImageFileExtension = sourceImageFile.Extension.Trim('.'); var isSourceFileSupported = Enum.TryParse <MagickFormat>(sourceImageFileExtension, true, out var format); if (isSourceFileSupported) { using (var image = new MagickImage()) { try { image.Read(sourceImageFile); } // Something went wrong while loading the image with ImageMagick catch (MagickException exception) { this.logger.LogError($"Error while loading image: {exception}"); await this.next(context); return; } image.Resize(sizeSetting.Width, sizeSetting.Height); image.Strip(); if (sizeSetting.Quality >= 0) { this.logger.LogInformation($"Setting Quality to: \"{sizeSetting.Quality}\""); image.Quality = sizeSetting.Quality; } if (sizeSetting.Progressive) { image.Format = MagickFormat.Pjpeg; } using (var stream = new MemoryStream()) { image.Write(stream); stream.Position = 0; this.logger.LogInformation($"LosslessCompress before: {stream.Length / 1024} kb"); var imageOptimizer = new ImageOptimizer(); if (options.LosslessCompress) { imageOptimizer.LosslessCompress(stream); } else { imageOptimizer.Compress(stream); } this.logger.LogInformation($"LosslessCompress after: {stream.Length / 1024} kb"); using ( FileStream file = new FileStream( imagePath, FileMode.Create, System.IO.FileAccess.Write ) ) { stream.WriteTo(file); file.Flush(); } } } } else { this.logger.LogSourceFileTypeNotSupported($"{sourceImageFileExtension}"); await this.next(context); return; } } } await this.next(context); }
public void LossyCompress(string path) { _imageOptimizer.Compress(path); }
private static bool TrySaveImage( DirectoryInfo imgDir, string imgName, ImageOptimizer optimizer, bool compressGifs, FileInfo fileInfo, out string outputImagePath) { outputImagePath = string.Empty; var imageFileInfo = imgDir.GetFiles($"{imgName}.*").FirstOrDefault(); if (!imageFileInfo.Exists) { return(false); } try { using (Image image = Image.FromFile(imageFileInfo.FullName)) using (MemoryStream m = new MemoryStream()) { image.Save(m, image.RawFormat); var oldSize = m.Length; var ext = imageFileInfo.Extension.ToLower(); //the simple optimizer fails with animated gifs, or gifs that have already been semi optimized (different size frames) if (optimizer != null && ext != ".gif") { m.Position = 0; optimizer.Compress(m); } if (compressGifs && ext == ".gif") { using (MagickImageCollection images = new MagickImageCollection(imageFileInfo)) { //I've disabled these optimization steps for now because they are extremely slow. //quantization is much faster and produces mostly very good results. (though not lossless) //images.Coalesce(); //images.Optimize(); //images.OptimizeTransparency(); //reduce color bit depth from 8 to 5. images.Quantize(new QuantizeSettings() { Colors = 32768 }); m.Position = 0; m.SetLength(0); images.Write(m); //in the case where gif compression fails to create a gif that is smaller //fallback to the old image stream. if (m.Length > oldSize) { m.Position = 0; m.SetLength(0); image.Save(m, image.RawFormat); } } } var newsize = m.Length; Program.VerboseControlLog($"reduced {imageFileInfo.Name} from {oldSize} to {newsize} ~{ (int)(100.0 - (((float)newsize / (float)oldSize) * 100.0))}% reduction"); var img = Image.FromStream(m); var fileName = $"{Path.GetFileNameWithoutExtension(fileInfo.FullName)}_img{imageFileInfo.Extension}"; var path = Path.Combine(fileInfo.Directory.FullName, fileName); img.Save(path); outputImagePath = $"![{imgName}](./{fileName.Replace(" ", "%20")})"; return(true); } } catch (Exception e) { Console.WriteLine(e); return(false); } }