/// <summary> /// 通过指定的 CompressOption 实例执行单个文件压缩 /// </summary> /// <param name="option"></param> /// <exception cref="NotSupportedException">Image.FromFile 引发的 OutOfMemoryException</exception> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="System.ArgumentException"></exception> public static void CompressSingle(string filename, string outputPath, ICompressOption option) { Image img; try { img = Image.FromFile(filename); } /* OutOfMemoryException * The file does not have a valid image format. * -or- * GDI+ does not support the pixel format of the file. * --MSDN : https://docs.microsoft.com/en-us/dotnet/api/system.drawing.image.fromfile?view=dotnet-plat-ext-3.1 */ catch (OutOfMemoryException e) { throw new NotSupportedException("Not Supported file format or out of memory.(Mostly the former)", e); } var output = new Bitmap(img.Size.Width, img.Size.Height); Graphics g = Graphics.FromImage(output); g.DrawImage(img, new Rectangle(0, 0, img.Size.Width, img.Size.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); g.Dispose(); img.Dispose(); var codec = GetCodecInfo(ImageFormat.Jpeg); var eps = GetQualityEncoderParameters(option.Quality); var realPath = outputPath.IsDirectory() ? Path.Combine(outputPath, Path.GetFileNameWithoutExtension(filename)) + ".jpg" : outputPath;//outputPath could be either a directory or a file path. output.Save(realPath, codec, eps); output.Dispose(); }
public static CompressOption FromInterface(ICompressOption iOption) => (CompressOption)iOption;