public static void Encode(string inPath, string outPath, int q, Subsampling subsampling, bool printSubsampling = true) { try { Bitmap bmp = (Bitmap)IOUtils.GetImage(inPath); var compressor = new TJCompressor(); byte[] compressed; TJSubsamplingOption subSample = TJSubsamplingOption.Chrominance420; if (subsampling == Subsampling.Chroma422) { subSample = TJSubsamplingOption.Chrominance422; } if (subsampling == Subsampling.Chroma444) { subSample = TJSubsamplingOption.Chrominance444; } if (printSubsampling) { Program.Print("-> Chroma Subsampling: " + subSample.ToString().Replace("Chrominance", "")); } compressed = compressor.Compress(bmp, subSample, q, TJFlags.None); File.WriteAllBytes(outPath, compressed); //Program.Print("[MozJpeg] Written image to " + outPath); } catch (Exception e) { Program.Print("MozJpeg Error: " + e.Message); } }
public static void Encode(string inPath, string outPath, int q, bool chromaSubSample = true) { try { Bitmap bmp = (Bitmap)ImgUtils.GetImage(inPath); var commpressor = new TJCompressor(); byte[] compressed; TJSubsamplingOption subSample = TJSubsamplingOption.Chrominance420; if (!chromaSubSample) { subSample = TJSubsamplingOption.Chrominance444; } compressed = commpressor.Compress(bmp, subSample, q, TJFlags.None); File.WriteAllBytes(outPath, compressed); Logger.Log("[MozJpeg] Written image to " + outPath); } catch (TypeInitializationException e) { Logger.ErrorMessage($"MozJpeg Initialization Error: {e.InnerException.Message}\n", e); } catch (Exception e) { Logger.ErrorMessage("MozJpeg Error: ", e); } }
/// <summary> /// This API usage is optimized for multiple runs of the same image size, by reusing the byte arrays instead of allocating new ones for every operation. /// </summary> private static void benchTJOptimized() { byte[] data = File.ReadAllBytes(inputFilePath); byte[] recompressed; int recompressedSize = 0; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); using (TJDecompressor decomp = new TJDecompressor(data)) { // Optimize by pre-allocating the buffers and re-using them. byte[] rawImg = new byte[decomp.getWidth() * decomp.getHeight() * TJ.getPixelSize(PixelFormat.RGB)]; recompressed = new byte[TJ.bufSize(decomp.getWidth(), decomp.getHeight(), decomp.getSubsamp())]; using (TJCompressor comp = new TJCompressor(rawImg, decomp.getWidth(), decomp.getHeight())) { comp.setJPEGQuality(jpegQuality); for (int i = 0; i < numIterations; i++) { decomp.decompress(rawImg); comp.compress(ref recompressed, Flag.NONE); } recompressedSize = comp.getCompressedSize(); } } sw.Stop(); PrintBenchmarkResult("turbojpegCLI optimized", sw.ElapsedMilliseconds); using (FileStream fs = new FileStream("out-libjpeg-turbo-optimized.jpg", FileMode.Create)) { fs.Write(recompressed, 0, recompressedSize); } }
public static byte[] PackScreenCaptureData(Bitmap image, Rectangle bounds) { byte[] results = {}; try { using (var compressor = new TJCompressor()) using (var screenStream = new MemoryStream()) using (var binaryWriter = new BinaryWriter(screenStream)) { binaryWriter.Write(Id); //write the x and y coords of the binaryWriter.Write(bounds.X); binaryWriter.Write(bounds.Y); //write the rect data binaryWriter.Write(bounds.Top); binaryWriter.Write(bounds.Bottom); binaryWriter.Write(bounds.Left); binaryWriter.Write(bounds.Right); var imageData = compressor.Compress(image, TJSubsamplingOptions.TJSAMP_420, 50, TJFlags.FASTDCT); binaryWriter.Write(imageData); results = screenStream.ToArray(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(results); }
public void SetUp() { _compressor = new TJCompressor(); if (Directory.Exists(OutDirectory)) { Directory.Delete(OutDirectory, true); } Directory.CreateDirectory(OutDirectory); }
public TJCompressorTests() { this.compressor = new TJCompressor(); if (Directory.Exists(this.OutDirectory)) { Directory.Delete(this.OutDirectory, true); } Directory.CreateDirectory(this.OutDirectory); }
public JpegDiffVideoEncoder() { decoder = new JpegDiffVideoDecoder(); decomp = new TJDecompressor(); comp = new TJCompressor(); decoderThread = new Thread(decoderThreadLoop); decoderThread.IsBackground = true; decoderThread.Name = "JpegDiffVideoEncoder Decoder Thread"; decoderThread.Start(); }
public void SetUp() { TJInitializer.Initialize(logger: Console.WriteLine); _compressor = new TJCompressor(); if (Directory.Exists(OutDirectory)) { Directory.Delete(OutDirectory, true); } Directory.CreateDirectory(OutDirectory); }
public TurboJpgImageCompression(bool decompress) { _decompress = decompress; if (decompress) { _decompressor = new TJDecompressor(); } else { _compressor = new TJCompressor(); } }
public ActionResult Compress(string path) { using (var bmp = new Bitmap(path)) { using (var tjc = new TJCompressor()) { var compressed = tjc.Compress(bmp, TJSubsamplingOption.Chrominance420, 85, TJFlags.None); var outPath = Path.Combine(Path.GetDirectoryName(path), $"compressed-", Path.GetFileName(path)); System.IO.File.WriteAllBytes(outPath, compressed); } } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
/// <summary> /// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="image">The <see cref="Image{TPixel}"/> to encode from.</param> /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param> public void Encode <TPixel>(Image <TPixel> image, Stream stream) where TPixel : struct, IPixel <TPixel> { var subsample = this.Subsample ?? (this.Quality >= 91 ? JpegSubsample.Ratio444 : JpegSubsample.Ratio420); var bytes = MemoryMarshal.AsBytes(image.Frames.RootFrame.PixelBuffer.Span); var compressor = new TJCompressor(); var result = compressor.Compress( bytes.ToArray(), image.Width * 4, image.Width, image.Height, PixelFormat.Format32bppArgb, subsample == JpegSubsample.Ratio420 ? TJSubsamplingOptions.TJSAMP_420 : TJSubsamplingOptions.TJSAMP_422, this.Quality, TJFlags.FASTDCT); stream.Write(result, 0, result.Length); }
public override double Encode(List <byte[]> JList, object CompressionQuality, bool debugInfoIsOn = false) { Console.WriteLine(); Console.WriteLine("Converting by libJPEG Turbo to JPG"); double avgtime = 0; double delta; int i = 0; var compressor = new TJCompressor(); foreach (byte[] bitmap in JList) { MemoryStream stream = new MemoryStream(); Image img = Image.FromStream(new MemoryStream(bitmap)); var sourceImage = (Bitmap)img; var width = img.Width; var height = img.Height; byte[] output; DateTime start = DateTime.Now; output = compressor.Compress(sourceImage, TJSubsamplingOptions.TJSAMP_420, Convert.ToInt32(CompressionQuality), TJFlags.FASTUPSAMPLE); DateTime finish = DateTime.Now; delta = (finish - start).TotalMilliseconds; avgtime += delta; using (FileStream file = new FileStream("output\\libJPEGTurbo" + i.ToString() + ".jpg", FileMode.Create, System.IO.FileAccess.Write)) { file.Write(output, 0, output.Length); } if (debugInfoIsOn) { Console.WriteLine("Done converting image {0}. Size: {1}. Time: {2} ms", i, img.Size, delta); } i++; } Console.WriteLine("..done."); return(avgtime); }
// Start is called before the first frame update void Start() { TJDecompressor decompressor = new TJDecompressor(); TJCompressor compressor = new TJCompressor(); byte[] compressedImage = File.ReadAllBytes("Assets/Images/image.jpg"); float startTime = Time.realtimeSinceStartup; DecompressedImage decompressedImage = decompressor.Decompress(compressedImage, TJPixelFormat.RGBA, TJFlags.None); Debug.Log("Image decompressed. Execution time : " + (Time.realtimeSinceStartup - startTime).ToString() + " secondes."); startTime = Time.realtimeSinceStartup; byte[] recompressedImage = compressor.Compress(decompressedImage.Data, decompressedImage.Stride, decompressedImage.Width, decompressedImage.Height, decompressedImage.PixelFormat, TJSubsamplingOption.Chrominance420, 92, TJFlags.None); Debug.Log("Image recompressed. Execution time : " + (Time.realtimeSinceStartup - startTime).ToString() + " secondes."); File.WriteAllBytes("Assets/Images/recompressedImage.jpg", recompressedImage); Debug.Log("Recompressed image saved at : Assets/Images/recompressedImage.jpg"); ; }
private static void JpegTurboCompression() { var sw = new Stopwatch(); var sourceImage = (Bitmap)Image.FromFile(@"D:\Downloads\1.jpg"); var width = sourceImage.Width; var height = sourceImage.Height; long average = 0; var iterations = 0; var compressor = new TJCompressor(); try { Console.WriteLine("Using libjpeg turbo"); while (!_stop) { sw.Restart(); compressor.Compress(sourceImage, TJSubsamplingOptions.TJSAMP_GRAY, Quality, TJFlags.BOTTOMUP); sw.Stop(); var sleepValue = 1000 / 25.0 - sw.ElapsedMilliseconds; if (sleepValue < 0) { sleepValue = 0; } average += sw.ElapsedMilliseconds; iterations++; Thread.Sleep((int)sleepValue); } Console.WriteLine("Average compression time for image {0}x{1} is {2:f3} ms. Iterations count {3}", width, height, (double)average / iterations, iterations); } finally { compressor.Dispose(); sourceImage.Dispose(); Wait.Set(); } }
private static void JpegTurboCompression() { var sw = new Stopwatch(); var sourceImage = (Bitmap)Image.FromFile(@"D:\Downloads\1.jpg"); var width = sourceImage.Width; var height = sourceImage.Height; long average = 0; var iterations = 0; var compressor = new TJCompressor(); try { Console.WriteLine("Using libjpeg turbo"); while (!_stop) { sw.Restart(); compressor.Compress(sourceImage, TJSubsamplingOptions.TJSAMP_GRAY, Quality, TJFlags.BOTTOMUP); sw.Stop(); var sleepValue = 1000 / 25.0 - sw.ElapsedMilliseconds; if (sleepValue < 0) sleepValue = 0; average += sw.ElapsedMilliseconds; iterations++; Thread.Sleep((int)sleepValue); } Console.WriteLine("Average compression time for image {0}x{1} is {2:f3} ms. Iterations count {3}", width, height, (double)average / iterations, iterations); } finally { compressor.Dispose(); sourceImage.Dispose(); Wait.Set(); } }
/// <summary> /// Writes the DirtyImageFragment to the data stream in compressed format. /// </summary> /// <param name="s">The stream to write the frame to.</param> /// <param name="compressor">A TJCompressor instance that is preconfigured with quality and subsampling options. Can be null if the image is already compressed.</param> /// <param name="compressToBuffer">The buffer to compress to, not used if the image is already compressed.</param> public void WriteToDataStream(IDataStream s, TJCompressor compressor, ref byte[] compressToBuffer) { s.WriteInt16((short)bounds.X); s.WriteInt16((short)bounds.Y); s.WriteUInt16((ushort)bounds.Width); s.WriteUInt16((ushort)bounds.Height); if (screenshot.BufferIsCompressed) { s.WriteInt32(screenshot.Buffer.Length); // Write length of image s.Write(screenshot.Buffer, 0, screenshot.Buffer.Length); // Write image } else { turbojpegCLI.PixelFormat pixelFormat = screenshot.BitsPerPixel == 24 ? turbojpegCLI.PixelFormat.BGR : turbojpegCLI.PixelFormat.BGRX; compressor.setSourceImage(screenshot.Buffer, 0, 0, screenshot.Width, screenshot.Stride, screenshot.Height, pixelFormat); compressor.compress(ref compressToBuffer, turbojpegCLI.Flag.NONE); int compressedSize = compressor.getCompressedSize(); s.WriteInt32(compressedSize); // Write length of image s.Write(compressToBuffer, 0, compressedSize); // Write image } }
private static void benchTJSimpleAPI() { byte[] data = File.ReadAllBytes(inputFilePath); byte[] rawImg = null; byte[] recompressed = null; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); using (TJDecompressor decomp = new TJDecompressor(data)) { using (TJCompressor comp = new TJCompressor()) { comp.setJPEGQuality(jpegQuality); for (int i = 0; i < numIterations; i++) { rawImg = decomp.decompress(); comp.setSourceImage(rawImg, decomp.getWidth(), decomp.getHeight()); recompressed = comp.compressToExactSize(); } } } sw.Stop(); PrintBenchmarkResult("turbojpegCLI simple API", sw.ElapsedMilliseconds); File.WriteAllBytes("out-libjpeg-turbo.jpg", recompressed); }
private static void JpegTurboCompression() { var sw = new Stopwatch(); var sourceImage = (Bitmap)Image.FromFile(@"d:\1.jpg"); var pixelFormat = sourceImage.PixelFormat; var width = sourceImage.Width; var height = sourceImage.Height; long average = 0; var iterations = 0; var compressor = new TJCompressor(); // ReSharper disable once ExceptionNotDocumented var srcData = sourceImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat); var stride = srcData.Stride; var srcPtr = srcData.Scan0; TJPixelFormats tjPixelFormat; switch (pixelFormat) { case PixelFormat.Format8bppIndexed: tjPixelFormat = TJPixelFormats.TJPF_GRAY; break; case PixelFormat.Format24bppRgb: tjPixelFormat = TJPixelFormats.TJPF_RGB; break; case PixelFormat.Format32bppArgb: tjPixelFormat = TJPixelFormats.TJPF_ARGB; break; default: throw new ArgumentOutOfRangeException(); } try { Console.WriteLine("Using libjpeg turbo"); while (!_stop) { sw.Restart(); compressor.Compress(srcPtr, stride, width, height, tjPixelFormat, TJSubsamplingOptions.TJSAMP_GRAY, Quality, TJFlags.BOTTOMUP); sw.Stop(); var sleepValue = 1000 / 25.0 - sw.ElapsedMilliseconds; if (sleepValue < 0) { sleepValue = 0; } average += sw.ElapsedMilliseconds; iterations++; Thread.Sleep((int)sleepValue); } Console.WriteLine("Average compression time for image {0}x{1} is {2:f3} ms. Iterations count {3}", width, height, (double)average / iterations, iterations); } finally { sourceImage.UnlockBits(srcData); compressor.Dispose(); sourceImage.Dispose(); Wait.Set(); } }