private IOptimizerResult ProcessStream(byte[] imageBytes) { if (imageBytes == null) { return(new PngOptimizerResult { SizeBefore = 0, SizeAfter = 0, Success = true }); } IntPtr pngOptimizer = GetOrLoadPngOptimizer(); byte[] resultBytes = new byte[imageBytes.Length + 400000]; int resultSize; IntPtr addressOfOptimize = NativeMethods.GetProcAddress(pngOptimizer, "PO_OptimizeFileMem"); if (addressOfOptimize == IntPtr.Zero) { throw new Exception("Can't find optimize funtion in PngOptimizerDll.dll!"); } OptimizeBytes optimizeMethod = (OptimizeBytes)Marshal.GetDelegateForFunctionPointer(addressOfOptimize, typeof(OptimizeBytes)); bool success = optimizeMethod(imageBytes, imageBytes.Length, resultBytes, resultBytes.Length, out resultSize); var result = new PngOptimizerResult { Success = success, SizeBefore = imageBytes.Length, SizeAfter = resultSize, }; if (result.SizeBefore > result.SizeAfter) { result.OptimizedBytes = resultBytes.Take(resultSize).ToArray(); } if (result.Success) { return(result); } IntPtr addressOfGetError = NativeMethods.GetProcAddress(pngOptimizer, "PO_GetLastErrorString"); if (addressOfGetError == IntPtr.Zero) { throw new Exception("Can't find get last error funtion in PngOptimizerDll.dll!"); } GetLastErrorString errorMethod = (GetLastErrorString)Marshal.GetDelegateForFunctionPointer(addressOfGetError, typeof(GetLastErrorString)); result.ErrorMessage = errorMethod(); return(result); }
public override IOptimizerResult Optimize(MediaStream stream) { IntPtr pngOptimizer = GetOrLoadPngOptimizer(); using (var memoryStream = new MemoryStream()) { stream.Stream.CopyTo(memoryStream); byte[] imageBytes = memoryStream.ToArray(); byte[] resultBytes = new byte[imageBytes.Length + 400000]; int resultSize; IntPtr addressOfOptimize = NativeMethods.GetProcAddress(pngOptimizer, "PO_OptimizeFileMem"); if (addressOfOptimize == IntPtr.Zero) { throw new Exception("Can't find optimize funtion in PngOptimizerDll.dll!"); } OptimizeBytes optimizeMethod = (OptimizeBytes)Marshal.GetDelegateForFunctionPointer(addressOfOptimize, typeof(OptimizeBytes)); bool success = optimizeMethod(imageBytes, imageBytes.Length, resultBytes, resultBytes.Length, out resultSize); var result = new PngOptimizerResult(); result.Success = success; result.SizeBefore = imageBytes.Length; result.SizeAfter = resultSize; result.OptimizedBytes = resultBytes.Take(resultSize).ToArray(); if (!result.Success) { IntPtr addressOfGetError = NativeMethods.GetProcAddress(pngOptimizer, "PO_GetLastErrorString"); if (addressOfGetError == IntPtr.Zero) { throw new Exception("Can't find get last error funtion in PngOptimizerDll.dll!"); } GetLastErrorString errorMethod = (GetLastErrorString)Marshal.GetDelegateForFunctionPointer(addressOfGetError, typeof(GetLastErrorString)); result.ErrorMessage = errorMethod(); } return(OptimizationSuccessful(result)); } }