public JpegCompressor() { var handle = JpegLibrary.tjInitCompress(); if (handle == IntPtr.Zero) { GetErrorAndThrow(); } SetResourceHandle(handle); }
/// <summary> /// Compresses the bitmap to an output buffer, returning the length if the compressed data /// </summary> /// <remarks> /// The buffer is re-allocated if too small, and can be larger than the compressed data! /// </remarks> public int Compress( ref byte[] buffer, int bufferOffset, IntPtr srcPtr, int stride, int width, int height, PixelFormat pixelFormat, int quality) { lock (this) { var bufferHandle = ObtainHandleUnderLock(); TJPixelFormats srcFormat = ConvertPixelFormat(pixelFormat); JpegLibrary.CheckOptionsCompatibilityAndThrow(SubSampling, srcFormat); ulong jpegSize = (ulong)MaxBufferSize; lock (_compressor) { var compressorHandle = _compressor.ObtainHandleUnderLock(); if (JpegLibrary.tjCompress2(compressorHandle, srcPtr, width, stride, height, (int)srcFormat, ref bufferHandle, ref jpegSize, (int)SubSampling, quality, (int)(TJFlags.NOREALLOC | TJFlags.FASTDCT)) == -1) { GetErrorAndThrow(); } int length = (int)jpegSize; if (buffer == null || buffer.Length < (bufferOffset + length)) { Array.Resize(ref buffer, bufferOffset + MaxBufferSize); } Marshal.Copy(bufferHandle, buffer, bufferOffset, length); return(length); } } }
public JpegFrame(JpegCompressor compressor, int width, int height, TJSubsamplingOptions subSampling) { _compressor = compressor; checked { Width = width; Height = height; SubSampling = subSampling; MaxBufferSize = (int)JpegLibrary.tjBufSize(width, height, (int)subSampling); } var bufferHandle = JpegLibrary.tjAlloc(MaxBufferSize); if (bufferHandle == IntPtr.Zero) { throw new OutOfMemoryException( $"Failed to allocate TurboJPEG buffer of size {width}x{height}, subSampling {subSampling}"); } SetResourceHandle(bufferHandle); }
protected override void Free(IntPtr handle) { JpegLibrary.tjDestroy(handle); }
public static void GetErrorAndThrow() { throw new TJException(JpegLibrary.tjGetErrorStr()); }
protected override void Free(IntPtr handle) { _compressor = null; JpegLibrary.tjFree(handle); }