Exemple #1
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcImage"> Source image to be converted. </param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="byte"/> array containing the compressed image.
        /// </returns>
        /// <remarks>Only <see cref="PixelFormat.Format24bppRgb"/>, <see cref="PixelFormat.Format32bppArgb"/>, <see cref="PixelFormat.Format8bppIndexed"/> pixel formats are supported.</remarks>
        /// <exception cref="TJException"> Throws if compress function failed. </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public byte[] Compress(Bitmap srcImage, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException("this");
            }

            var pixelFormat = srcImage.PixelFormat;

            var width   = srcImage.Width;
            var height  = srcImage.Height;
            var srcData = srcImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);

            var stride = srcData.Stride;
            var srcPtr = srcData.Scan0;

            try
            {
                return(this.Compress(srcPtr, stride, width, height, pixelFormat, subSamp, quality, flags));
            }
            finally
            {
                srcImage.UnlockBits(srcData);
            }
        }
Exemple #2
0
 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);
     }
 }
Exemple #3
0
        public void CompressByteArray(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                try
                {
                    var stride      = bitmap.RowBytes;
                    var width       = bitmap.Width;
                    var height      = bitmap.Height;
                    var pixelFormat = TJSkiaUtils.ConvertPixelFormat(bitmap.ColorType);

                    var buf = bitmap.GetPixelSpan().ToArray();

                    Trace.WriteLine($"Options: {options}; Quality: {quality}");
                    var result = this.compressor.Compress(buf, stride, width, height, pixelFormat, options, quality, TJFlags.None);
                    Assert.NotNull(result);
                }
                finally
                {
                    bitmap.Dispose();
                }
            }
        }
        public void CompressBitmap(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            var imageidx = 0;

            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                try
                {
                    Trace.WriteLine($"Options: {options}; Quality: {quality}");

                    var result = this.compressor.Compress(bitmap, options, quality, TJFlags.None);

                    Assert.NotNull(result);

                    var file = Path.Combine(this.OutDirectory, $"{imageidx}_{quality}_{options}.jpg");
                    File.WriteAllBytes(file, result);
                }
                finally
                {
                    bitmap.Dispose();
                }

                imageidx++;
            }
        }
Exemple #5
0
        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);
            }
        }
Exemple #6
0
 public void CompressIntPtr(
     [CombinatorialValues(
          TJSubsamplingOption.Gray,
          TJSubsamplingOption.Chrominance411,
          TJSubsamplingOption.Chrominance420,
          TJSubsamplingOption.Chrominance440,
          TJSubsamplingOption.Chrominance422,
          TJSubsamplingOption.Chrominance444)]
     TJSubsamplingOption options,
     [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
     int quality)
 {
     foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
     {
         try
         {
             Trace.WriteLine($"Options: {options}; Quality: {quality}");
             var result = this.compressor.Compress(bitmap.GetPixels(), bitmap.RowBytes, bitmap.Width, bitmap.Height, TJSkiaUtils.ConvertPixelFormat(bitmap.ColorType), options, quality, TJFlags.None);
             Assert.NotNull(result);
         }
         finally
         {
             bitmap.Dispose();
         }
     }
 }
Exemple #7
0
        public unsafe void CompressSpanToSpan(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                try
                {
                    var stride      = bitmap.RowBytes;
                    var width       = bitmap.Width;
                    var height      = bitmap.Height;
                    var pixelFormat = TJSkiaUtils.ConvertPixelFormat(bitmap.ColorType);

                    var buf = bitmap.GetPixelSpan();

                    Trace.WriteLine($"Options: {options}; Quality: {quality}");
                    Span <byte> target = new byte[this.compressor.GetBufferSize(width, height, options)];

                    this.compressor.Compress(buf, target, stride, width, height, pixelFormat, options, quality, TJFlags.None);
                }
                finally
                {
                    bitmap.Dispose();
                }
            }
        }
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcPtr">
        /// Pointer to an image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="byte"/> array containing the compressed image.
        /// </returns>
        /// <exception cref="TJException"> Throws if compress function failed. </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public static byte[] Compress(this TJCompressor @this, IntPtr srcPtr, int stride, int width, int height, PixelFormat pixelFormat,
                                      TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            _ = @this ?? throw new ArgumentNullException(nameof(@this));
            var tjPixelFormat = TJGdiPlusUtils.ConvertPixelFormat(pixelFormat);

            return(@this.Compress(srcPtr, stride, width, height, tjPixelFormat, subSamp, quality, flags));
        }
Exemple #9
0
 /// <exception cref="NotSupportedException">
 /// Some parameters' values are incompatible:
 /// <list type="bullet">
 /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
 /// </list>
 /// </exception>
 private static void CheckOptionsCompatibilityAndThrow(TJSubsamplingOption subSamp, TJPixelFormat srcFormat)
 {
     if (srcFormat == TJPixelFormat.Gray && subSamp != TJSubsamplingOption.Gray)
     {
         throw new NotSupportedException(
                   $"Subsampling differ from {TJSubsamplingOption.Gray} for pixel format {TJPixelFormat.Gray} is not supported");
     }
 }
Exemple #10
0
        /// <summary>
        /// Compress a set of Y, U (Cb), and V (Cr) image planes into a JPEG image.
        /// </summary>
        /// <param name="yPlane">
        /// A pointer to the Y image planes of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="uPlane">
        /// A pointer to the U (Cb) image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="vPlane">
        /// A pointer to the V (Cr)image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="width">
        /// The width (in pixels) of the source image. If the width is not an even multiple of the MCU block width (see tjMCUWidth), then an intermediate buffer copy will be performed within TurboJPEG.
        /// </param>
        /// <param name="strides">
        /// An array of integers, each specifying the number of bytes per line in the corresponding plane of the YUV source image.
        /// Setting the stride for any plane to 0 is the same as setting it to the plane width (see YUV Image Format Notes.)
        /// If strides is <see langword="null"/>, then the strides for all planes will be set to their respective plane widths.
        /// You can adjust the strides in order to specify an arbitrary amount of line padding in each plane or to decode a subregion of a larger YUV planar image.
        /// </param>
        /// <param name="height">
        /// The height (in pixels) of the source image. If the height is not an even multiple of the MCU block height (see tjMCUHeight), then an intermediate buffer copy will be performed within TurboJPEG.
        /// </param>
        /// <param name="subsamp">
        /// The level of chrominance subsampling used in the source image (see Chrominance subsampling options.)
        /// </param>
        /// <param name="jpegBuf">
        /// A pointer to an image buffer that will receive the JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to accommodate the size of the JPEG image. Thus, you can choose to:
        /// <list type="number">
        ///   <item>
        ///      pre-allocate the JPEG buffer with an arbitrary size using <see cref="TJUtils.Alloc"/> and let TurboJPEG grow the buffer as needed,
        ///   </item>
        ///   <item>
        ///     set* jpegBuf to NULL to tell TurboJPEG to allocate the buffer for you, or
        ///   </item>
        ///   <item>
        ///     pre-allocate the buffer to a "worst case" size determined by calling tjBufSize(). This should ensure that the buffer never has to be re-allocated(setting TJFLAG_NOREALLOC guarantees that it won't be.)
        ///   </item>
        /// </list>
        /// If you choose option 1, * jpegSize should be set to the size of your pre-allocated buffer. In any case, unless you have set TJFLAG_NOREALLOC, you should always check *jpegBuf upon return from this function, as it may have changed.
        /// </param>
        /// <param name="jpegQual">
        /// The image quality of the generated JPEG image (1 = worst, 100 = best).
        /// </param>
        /// <param name="flags">
        /// The bitwise OR of one or more of the flags.
        /// </param>
        /// <returns>
        /// A <see cref="Span{byte}"/> which holds the compressed image.
        /// </returns>
        public unsafe Span <byte> CompressFromYUVPlanes(
            Span <byte> yPlane,
            Span <byte> uPlane,
            Span <byte> vPlane,
            int width,
            int[] strides,
            int height,
            TJSubsamplingOption subsamp,
            Span <byte> jpegBuf,
            int jpegQual,
            TJFlags flags)
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(nameof(TJCompressor));
            }

            uint   destBufSize = (uint)jpegBuf.Length;
            IntPtr jpegBufPtr2 = IntPtr.Zero;

            fixed(byte *yPlanePtr = yPlane)
            fixed(byte *uPlanePtr = uPlane)
            fixed(byte *vPlanePtr = vPlane)
            {
                byte *[] planes = new byte *[] { yPlanePtr, uPlanePtr, vPlanePtr };

                fixed(int *stridesPtr = strides)
                fixed(byte *jpegBufPtr = jpegBuf)
                fixed(byte **planesPtr = planes)
                {
                    jpegBufPtr2 = (IntPtr)jpegBufPtr;

                    var result = TurboJpegImport.TjCompressFromYUVPlanes(
                        this.compressorHandle,
                        planesPtr,
                        width,
                        stridesPtr,
                        height,
                        (int)subsamp,
                        ref jpegBufPtr2,
                        ref destBufSize,
                        jpegQual,
                        (int)flags);

                    if (result == -1)
                    {
                        TJUtils.GetErrorAndThrow();
                    }
                }
            }

            return(new Span <byte>(jpegBufPtr2.ToPointer(), (int)destBufSize));
        }
Exemple #11
0
        public static byte[] Compress(this TJCompressor @this, SKBitmap srcImage, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            _ = @this ?? throw new ArgumentNullException(nameof(@this));
            _ = srcImage ?? throw new ArgumentNullException(nameof(srcImage));

            var tjPixelFormat = TJSkiaUtils.ConvertPixelFormat(srcImage.ColorType);

            var width  = srcImage.Width;
            var height = srcImage.Height;

            var srcPtr = srcImage.GetPixels();
            var stride = srcImage.RowBytes;

            return(@this.Compress(srcPtr, stride, width, height, tjPixelFormat, subSamp, quality, flags));
        }
Exemple #12
0
        /// <summary>
        /// Compress a set of Y, U (Cb), and V (Cr) image planes into a JPEG image.
        /// </summary>
        /// <param name="yPlane">
        /// A pointer to the Y image planes of the YUV image to be decoded.
        /// The size of the plane should match the value returned by <see cref="PlaneSizeYUV"/> for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="uPlane">
        /// A pointer to the U (Cb) image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by <see cref="PlaneSizeYUV"/> for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="vPlane">
        /// A pointer to the V (Cr)image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by <see cref="PlaneSizeYUV"/> for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="width">
        /// The width (in pixels) of the source image. If the width is not an even multiple of the MCU block width (see tjMCUWidth), then an intermediate buffer copy will be performed within TurboJPEG.
        /// </param>
        /// <param name="strides">
        /// An array of integers, each specifying the number of bytes per line in the corresponding plane of the YUV source image.
        /// Setting the stride for any plane to 0 is the same as setting it to the plane width (see YUV Image Format Notes.)
        /// If strides is <see langword="null"/>, then the strides for all planes will be set to their respective plane widths.
        /// You can adjust the strides in order to specify an arbitrary amount of line padding in each plane or to decode a subregion of a larger YUV planar image.
        /// </param>
        /// <param name="height">
        /// The height (in pixels) of the source image. If the height is not an even multiple of the MCU block height (see tjMCUHeight), then an intermediate buffer copy will be performed within TurboJPEG.
        /// </param>
        /// <param name="subsamp">
        /// The level of chrominance subsampling used in the source image (see Chrominance subsampling options.)
        /// </param>
        /// <param name="jpegBuf">
        /// A pointer to an image buffer that will receive the JPEG image. TurboJPEG has the ability to reallocate the JPEG buffer to accommodate the size of the JPEG image. Thus, you can choose to:
        /// <list type="number">
        ///   <item>
        ///      pre-allocate the JPEG buffer with an arbitrary size using <see cref="TurboJpegImport.TjAlloc"/> and let TurboJPEG grow the buffer as needed,
        ///   </item>
        ///   <item>
        ///     set* jpegBuf to NULL to tell TurboJPEG to allocate the buffer for you, or
        ///   </item>
        ///   <item>
        ///     pre-allocate the buffer to a "worst case" size determined by calling tjBufSize(). This should ensure that the buffer never has to be re-allocated(setting TJFLAG_NOREALLOC guarantees that it won't be.)
        ///   </item>
        /// </list>
        /// If you choose option 1, * jpegSize should be set to the size of your pre-allocated buffer. In any case, unless you have set TJFLAG_NOREALLOC, you should always check *jpegBuf upon return from this function, as it may have changed.
        /// </param>
        /// <param name="jpegQual">
        /// The image quality of the generated JPEG image (1 = worst, 100 = best).
        /// </param>
        /// <param name="flags">
        /// The bitwise OR of one or more of the flags.
        /// </param>
        /// <returns>
        /// A <see cref="Span{T}"/> which holds the compressed image.
        /// </returns>
        public unsafe Span <byte> CompressFromYUVPlanes(
            Span <byte> yPlane,
            Span <byte> uPlane,
            Span <byte> vPlane,
            int width,
            int[] strides,
            int height,
            TJSubsamplingOption subsamp,
            Span <byte> jpegBuf,
            int jpegQual,
            TJFlags flags)
        {
            Verify.NotDisposed(this);

            nuint  destBufSize = (nuint)jpegBuf.Length;
            IntPtr jpegBufPtr2 = IntPtr.Zero;

            fixed(byte *yPlanePtr = yPlane)
            fixed(byte *uPlanePtr = uPlane)
            fixed(byte *vPlanePtr = vPlane)
            {
                byte *[] planes = new byte *[] { yPlanePtr, uPlanePtr, vPlanePtr };

                fixed(int *stridesPtr = strides)
                fixed(byte *jpegBufPtr = jpegBuf)
                fixed(byte **planesPtr = planes)
                {
                    jpegBufPtr2 = (IntPtr)jpegBufPtr;

                    var result = TurboJpegImport.TjCompressFromYUVPlanes(
                        this.compressorHandle,
                        planesPtr,
                        width,
                        stridesPtr,
                        height,
                        (int)subsamp,
                        ref jpegBufPtr2,
                        ref destBufSize,
                        jpegQual,
                        (int)flags);

                    TJUtils.ThrowOnError(result);
                }
            }

            return(new Span <byte>(jpegBufPtr2.ToPointer(), (int)destBufSize));
        }
        /// <summary>
        /// Decode a set of Y, U (Cb), and V (Cr) image planes into an RGB or grayscale image.
        /// </summary>
        /// <param name="yPlane">
        /// A pointer to the Y image planes of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="uPlane">
        /// A pointer to the U (Cb) image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="vPlane">
        /// A pointer to the V (Cr)image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="strides">
        /// An array of integers, each specifying the number of bytes per line in the corresponding plane of the YUV source image.
        /// Setting the stride for any plane to 0 is the same as setting it to the plane width (see YUV Image Format Notes.)
        /// If strides is <see langword="null"/>, then the strides for all planes will be set to their respective plane widths.
        /// You can adjust the strides in order to specify an arbitrary amount of line padding in each plane or to decode a subregion of a larger YUV planar image.
        /// </param>
        /// <param name="subsamp">
        /// The level of chrominance subsampling used in the YUV source image (see Chrominance subsampling options.)
        /// </param>
        /// <param name="dstBuf">
        /// A pointer to an image buffer that will receive the decoded image. This buffer should normally be <paramref name="pitch"/> * <paramref name="height"/> bytes in size,
        /// but the <paramref name="dstBuf"/> pointer can also be used to decode into a specific region of a larger buffer.
        /// </param>
        /// <param name="width">
        /// Width (in pixels) of the source and destination images.
        /// </param>
        /// <param name="pitch">
        /// Bytes per line in the destination image. Normally, this should be <paramref name="width"/> * <c>tjPixelSize[pixelFormat]</c>
        /// if the destination image is unpadded, or <c>TJPAD(width * tjPixelSize[pixelFormat])</c> if each line of the destination image
        /// should be padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. You can also be clever and use the
        /// pitch parameter to skip lines, etc.
        /// Setting this parameter to <c>0</c> is the equivalent of setting it to <paramref name="width"/> * <c>tjPixelSize[pixelFormat]</c>.
        /// </param>
        /// <param name="height">
        /// Height (in pixels) of the source and destination images.
        /// </param>
        /// <param name="pixelFormat">
        /// Pixel format of the destination image.
        /// </param>
        /// <param name="flags">
        /// The bitwise OR of one or more of the flags.
        /// </param>
        /// <remarks>
        /// <para>
        /// This function uses the accelerated color conversion routines in the underlying codec but does not execute any of the other steps in the JPEG decompression process.
        /// </para>
        /// <para>
        /// The <paramref name="yPlane"/>, <paramref name="uPlane"/> and <paramref name="vPlane"/> planes can be contiguous or non-contiguous in memory.
        /// Refer to YUV Image Format Notes for more details.
        /// </para>
        /// </remarks>
        public unsafe void DecodeYUVPlanes(
            Span <byte> yPlane,
            Span <byte> uPlane,
            Span <byte> vPlane,
            int[] strides,
            TJSubsamplingOption subsamp,
            Span <byte> dstBuf,
            int width,
            int pitch,
            int height,
            TJPixelFormat pixelFormat,
            TJFlags flags)
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(nameof(TJDecompressor));
            }

            fixed(byte *yPlanePtr = yPlane)
            fixed(byte *uPlanePtr = uPlane)
            fixed(byte *vPlanePtr = vPlane)
            {
                byte *[] planes = new byte *[] { yPlanePtr, uPlanePtr, vPlanePtr };

                fixed(int *stridesPtr = strides)
                fixed(byte **planesPtr = planes)
                fixed(byte *dstBufPtr  = dstBuf)
                {
                    if (TurboJpegImport.TjDecodeYUVPlanes(
                            this.decompressorHandle,
                            planesPtr,
                            stridesPtr,
                            (int)subsamp,
                            (IntPtr)dstBufPtr,
                            width,
                            pitch,
                            height,
                            (int)pixelFormat,
                            (int)flags) == -1)
                    {
                        TJUtils.GetErrorAndThrow();
                    }
                }
            }
        }
Exemple #14
0
        public static byte[] Recompress(
            ReadOnlySpan <byte> jpegBytes,
            int quality = 70,
            TJSubsamplingOption subsampling = TJSubsamplingOption.Chrominance420,
            TJFlags flags = TJFlags.None)
        {
            var pixelFormat = TJPixelFormat.BGRA;

            using var decr = new TJDecompressor();
            var raw = decr.Decompress(jpegBytes, pixelFormat, flags, out var width, out var height, out var stride);

            decr.Dispose();

            using var compr = new TJCompressor();
            var compressed = compr.Compress(raw, stride, width, height, pixelFormat, subsampling, quality, flags);

            return(compressed);
        }
Exemple #15
0
 public void RecompressSpan(
     [CombinatorialValues(
          TJSubsamplingOption.Gray,
          TJSubsamplingOption.Chrominance411,
          TJSubsamplingOption.Chrominance420,
          TJSubsamplingOption.Chrominance440,
          TJSubsamplingOption.Chrominance422,
          TJSubsamplingOption.Chrominance444)]
     TJSubsamplingOption subsampling,
     [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
     int quality)
 {
     foreach (var data in TestUtils.GetTestImagesData("*.jpg"))
     {
         var compressed = MozJpeg.Recompress(data.Item2.AsSpan(), quality, subsampling);
         var fileName   = Path.GetFileName(data.Item1);
         Trace.WriteLine($"{fileName}; old#: {data.Item2.Length}; new#: {compressed.Length}; Ration: {compressed.Length / data.Item2.Length}; Subsampling: {subsampling}; Quality: {quality}");
     }
 }
Exemple #16
0
        public void CompressByteArrayToByteArray(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                try
                {
                    var data = bitmap.LockBits(
                        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                        ImageLockMode.ReadOnly,
                        bitmap.PixelFormat);

                    var stride      = data.Stride;
                    var width       = data.Width;
                    var height      = data.Height;
                    var pixelFormat = data.PixelFormat;
                    Assert.Equal(PixelFormat.Format24bppRgb, pixelFormat);

                    var buf = new byte[stride * height];
                    Marshal.Copy(data.Scan0, buf, 0, buf.Length);
                    bitmap.UnlockBits(data);

                    Trace.WriteLine($"Options: {options}; Quality: {quality}");
                    byte[] target = new byte[this.compressor.GetBufferSize(width, height, options)];

                    this.compressor.Compress(buf, target, stride, width, height, TJPixelFormat.RGB, options, quality, TJFlags.None);
                }
                finally
                {
                    bitmap.Dispose();
                }
            }
        }
Exemple #17
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcImage"> Source image to be converted. </param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="byte"/> array containing the compressed image.
        /// </returns>
        /// <remarks>Only <see cref="PixelFormat.Format24bppRgb"/>, <see cref="PixelFormat.Format32bppArgb"/>, <see cref="PixelFormat.Format8bppIndexed"/> pixel formats are supported.</remarks>
        /// <exception cref="TJException"> Throws if compress function failed. </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public static byte[] Compress(this TJCompressor @this, Bitmap srcImage, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            _ = @this ?? throw new ArgumentNullException(nameof(@this));
            var pixelFormat = srcImage.PixelFormat;

            var width   = srcImage.Width;
            var height  = srcImage.Height;
            var srcData = srcImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, pixelFormat);

            var stride = srcData.Stride;
            var srcPtr = srcData.Scan0;

            try
            {
                return(@this.Compress(srcPtr, stride, width, height, pixelFormat, subSamp, quality, flags));
            }
            finally
            {
                srcImage.UnlockBits(srcData);
            }
        }
Exemple #18
0
        /// <summary>
        /// Decode a set of Y, U (Cb), and V (Cr) image planes into an RGB or grayscale image.
        /// </summary>
        /// <param name="yPlane">
        /// A pointer to the Y image planes of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="uPlane">
        /// A pointer to the U (Cb) image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="vPlane">
        /// A pointer to the V (Cr)image plane (or just <see langword="null"/>, if decoding a grayscale image) of the YUV image to be decoded.
        /// The size of the plane should match the value returned by tjPlaneSizeYUV() for the given image width, height, strides, and level of chrominance subsampling.
        /// </param>
        /// <param name="strides">
        /// An array of integers, each specifying the number of bytes per line in the corresponding plane of the YUV source image.
        /// Setting the stride for any plane to 0 is the same as setting it to the plane width (see YUV Image Format Notes.)
        /// If strides is <see langword="null"/>, then the strides for all planes will be set to their respective plane widths.
        /// You can adjust the strides in order to specify an arbitrary amount of line padding in each plane or to decode a subregion of a larger YUV planar image.
        /// </param>
        /// <param name="subsamp">
        /// The level of chrominance subsampling used in the YUV source image (see Chrominance subsampling options.)
        /// </param>
        /// <param name="dstBuf">
        /// A pointer to an image buffer that will receive the decoded image. This buffer should normally be <paramref name="pitch"/> * <paramref name="height"/> bytes in size,
        /// but the <paramref name="dstBuf"/> pointer can also be used to decode into a specific region of a larger buffer.
        /// </param>
        /// <param name="width">
        /// Width (in pixels) of the source and destination images.
        /// </param>
        /// <param name="pitch">
        /// Bytes per line in the destination image. Normally, this should be <paramref name="width"/> * <c>tjPixelSize[pixelFormat]</c>
        /// if the destination image is unpadded, or <c>TJPAD(width * tjPixelSize[pixelFormat])</c> if each line of the destination image
        /// should be padded to the nearest 32-bit boundary, as is the case for Windows bitmaps. You can also be clever and use the
        /// pitch parameter to skip lines, etc.
        /// Setting this parameter to <c>0</c> is the equivalent of setting it to <paramref name="width"/> * <c>tjPixelSize[pixelFormat]</c>.
        /// </param>
        /// <param name="height">
        /// Height (in pixels) of the source and destination images.
        /// </param>
        /// <param name="pixelFormat">
        /// Pixel format of the destination image.
        /// </param>
        /// <param name="flags">
        /// The bitwise OR of one or more of the flags.
        /// </param>
        /// <remarks>
        /// <para>
        /// This function uses the accelerated color conversion routines in the underlying codec but does not execute any of the other steps in the JPEG decompression process.
        /// </para>
        /// <para>
        /// The <paramref name="yPlane"/>, <paramref name="uPlane"/> and <paramref name="vPlane"/> planes can be contiguous or non-contiguous in memory.
        /// Refer to YUV Image Format Notes for more details.
        /// </para>
        /// </remarks>
        public unsafe void DecodeYUVPlanes(
            Span <byte> yPlane,
            Span <byte> uPlane,
            Span <byte> vPlane,
            int[] strides,
            TJSubsamplingOption subsamp,
            Span <byte> dstBuf,
            int width,
            int pitch,
            int height,
            TJPixelFormat pixelFormat,
            TJFlags flags)
        {
            Verify.NotDisposed(this);

            fixed(byte *yPlanePtr = yPlane)
            fixed(byte *uPlanePtr = uPlane)
            fixed(byte *vPlanePtr = vPlane)
            {
                byte *[] planes = new byte *[] { yPlanePtr, uPlanePtr, vPlanePtr };

                fixed(int *stridesPtr = strides)
                fixed(byte **planesPtr = planes)
                fixed(byte *dstBufPtr  = dstBuf)
                {
                    TJUtils.ThrowOnError(
                        TurboJpegImport.TjDecodeYUVPlanes(
                            this.decompressorHandle,
                            planesPtr,
                            stridesPtr,
                            (int)subsamp,
                            (IntPtr)dstBufPtr,
                            width,
                            pitch,
                            height,
                            (int)pixelFormat,
                            (int)flags));
                }
            }
        }
Exemple #19
0
        public unsafe void CompressSpanToSpan(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                try
                {
                    var data = bitmap.LockBits(
                        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                        ImageLockMode.ReadOnly,
                        bitmap.PixelFormat);

                    var stride      = data.Stride;
                    var width       = data.Width;
                    var height      = data.Height;
                    var pixelFormat = data.PixelFormat;

                    Span <byte> buf = new Span <byte>((byte *)data.Scan0, stride * height);
                    bitmap.UnlockBits(data);

                    Trace.WriteLine($"Options: {options}; Quality: {quality}");
                    Span <byte> target = new byte[this.compressor.GetBufferSize(width, height, options)];

                    this.compressor.Compress(buf, target, stride, width, height, pixelFormat, options, quality, TJFlags.None);
                }
                finally
                {
                    bitmap.Dispose();
                }
            }
        }
        public void CompressIntPtr(
            [CombinatorialValues(
                 TJSubsamplingOption.Gray,
                 TJSubsamplingOption.Chrominance411,
                 TJSubsamplingOption.Chrominance420,
                 TJSubsamplingOption.Chrominance440,
                 TJSubsamplingOption.Chrominance422,
                 TJSubsamplingOption.Chrominance444)]
            TJSubsamplingOption options,
            [CombinatorialValues(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)]
            int quality)
        {
            foreach (var bitmap in TestUtils.GetTestImages("*.bmp"))
            {
                BitmapData data = null;
                try
                {
                    data = bitmap.LockBits(
                        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                        ImageLockMode.ReadOnly,
                        bitmap.PixelFormat);

                    Trace.WriteLine($"Options: {options}; Quality: {quality}");
                    var result = this.compressor.Compress(data.Scan0, data.Stride, data.Width, data.Height, data.PixelFormat, options, quality, TJFlags.None);
                    Assert.NotNull(result);
                }
                finally
                {
                    if (data != null)
                    {
                        bitmap.UnlockBits(data);
                    }

                    bitmap.Dispose();
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcBuf">
        /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="byte"/> array containing the compressed image.
        /// </returns>
        /// <exception cref="TJException">
        /// Throws if compress function failed.
        /// </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public unsafe byte[] Compress(byte[] srcBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException("this");
            }

            var tjPixelFormat = TJUtils.ConvertPixelFormat(pixelFormat);

            CheckOptionsCompatibilityAndThrow(subSamp, tjPixelFormat);

            var   buf     = IntPtr.Zero;
            ulong bufSize = 0;

            try
            {
                fixed(byte *srcBufPtr = srcBuf)
                {
                    var result = TurboJpegImport.TjCompress2(
                        this.compressorHandle,
                        (IntPtr)srcBufPtr,
                        width,
                        stride,
                        height,
                        (int)tjPixelFormat,
                        ref buf,
                        ref bufSize,
                        (int)subSamp,
                        quality,
                        (int)flags);

                    if (result == -1)
                    {
                        TJUtils.GetErrorAndThrow();
                    }
                }

                var jpegBuf = new byte[bufSize];

                Marshal.Copy(buf, jpegBuf, 0, (int)bufSize);
                return(jpegBuf);
            }
            finally
            {
                TurboJpegImport.TjFree(buf);
            }
        }
Exemple #22
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcBuf">
        /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="destBuf">
        /// A <see cref="byte"/> array containing the compressed image.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="TJPixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="Span{T}"/> which is a slice of <paramref name="destBuf"/> which holds the compressed image.
        /// </returns>
        /// <exception cref="TJException">
        /// Throws if compress function failed.
        /// </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public unsafe Span <byte> Compress(Span <byte> srcBuf, Span <byte> destBuf, int stride, int width, int height, TJPixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            Verify.NotDisposed(this);

            CheckOptionsCompatibilityAndThrow(subSamp, pixelFormat);

            ulong destBufSize = (ulong)destBuf.Length;

            fixed(byte *srcBufPtr = srcBuf)
            fixed(byte *destBufPtr = destBuf)
            {
                IntPtr destBufPtr2 = (IntPtr)destBufPtr;

                var result = TurboJpegImport.TjCompress2(
                    this.compressorHandle,
                    (IntPtr)srcBufPtr,
                    width,
                    stride,
                    height,
                    (int)pixelFormat,
                    ref destBufPtr2,
                    ref destBufSize,
                    (int)subSamp,
                    quality,
                    (int)flags);

                TJUtils.ThrowOnError(result);
            }

            return(destBuf.Slice(0, (int)destBufSize));
        }
Exemple #23
0
 /// <summary>
 /// Compresses input image to the jpeg format with specified quality.
 /// </summary>
 /// <param name="srcBuf">
 /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
 /// This buffer is not modified.
 /// </param>
 /// <param name="destBuf">
 /// A <see cref="byte"/> array containing the compressed image.
 /// </param>
 /// <param name="stride">
 /// Bytes per line in the source image.
 /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
 /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
 /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
 /// You can also be clever and use this parameter to skip lines, etc.
 /// Setting this parameter to 0 is the equivalent of setting it to
 /// <c>width * BytesPerPixel</c>.
 /// </param>
 /// <param name="width">Width (in pixels) of the source image.</param>
 /// <param name="height">Height (in pixels) of the source image.</param>
 /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
 /// <param name="subSamp">
 /// The level of chrominance subsampling to be used when
 /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
 /// </param>
 /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
 /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
 /// <returns>
 /// The size of the JPEG image (in bytes).
 /// </returns>
 /// <exception cref="TJException">
 /// Throws if compress function failed.
 /// </exception>
 /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
 /// <exception cref="NotSupportedException">
 /// Some parameters' values are incompatible:
 /// <list type="bullet">
 /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
 /// </list>
 /// </exception>
 public unsafe int Compress(byte[] srcBuf, byte[] destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
 {
     return(this.Compress(srcBuf.AsSpan(), destBuf.AsSpan(), stride, width, height, pixelFormat, subSamp, quality, flags).Length);
 }
Exemple #24
0
        /// <summary>
        /// The maximum size of the buffer (in bytes) required to hold a JPEG image with
        /// the given parameters.  The number of bytes returned by this function is
        /// larger than the size of the uncompressed source image.  The reason for this
        /// is that the JPEG format uses 16-bit coefficients, and it is thus possible
        /// for a very high-quality JPEG image with very high-frequency content to
        /// expand rather than compress when converted to the JPEG format.  Such images
        /// represent a very rare corner case, but since there is no way to predict the
        /// size of a JPEG image prior to compression, the corner case has to be handled.
        /// </summary>
        /// <param name="width">Width (in pixels) of the image.</param>
        /// <param name="height">Height (in pixels) of the image.</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image(see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <returns>
        /// The maximum size of the buffer (in bytes) required to hold the image,
        /// or -1 if the arguments are out of bounds.
        /// </returns>
        public int GetBufferSize(int width, int height, TJSubsamplingOption subSamp)
        {
            Verify.NotDisposed(this);

            return((int)TurboJpegImport.TjBufSize(width, height, (int)subSamp));
        }
Exemple #25
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcBuf">
        /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="destBuf">
        /// A <see cref="byte"/> array containing the compressed image.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="Span{T}"/> which is a slice of <paramref name="destBuf"/> which holds the compressed image.
        /// </returns>
        /// <exception cref="TJException">
        /// Throws if compress function failed.
        /// </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public unsafe Span <byte> Compress(Span <byte> srcBuf, Span <byte> destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            var tjPixelFormat = TJUtils.ConvertPixelFormat(pixelFormat);

            return(this.Compress(srcBuf, destBuf, stride, width, height, tjPixelFormat, subSamp, quality, flags));
        }
Exemple #26
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcBuf">
        /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="destBuf">
        /// A <see cref="byte"/> array containing the compressed image.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="Span{T}"/> which is a slice of <paramref name="destBuf"/> which holds the compressed image.
        /// </returns>
        /// <exception cref="TJException">
        /// Throws if compress function failed.
        /// </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public unsafe Span <byte> Compress(Span <byte> srcBuf, Span <byte> destBuf, int stride, int width, int height, TJPixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            if (this.isDisposed)
            {
                throw new ObjectDisposedException(nameof(TJCompressor));
            }

            CheckOptionsCompatibilityAndThrow(subSamp, pixelFormat);

            ulong destBufSize = (ulong)destBuf.Length;

            fixed(byte *srcBufPtr = srcBuf)
            fixed(byte *destBufPtr = destBuf)
            {
                IntPtr destBufPtr2 = (IntPtr)destBufPtr;

                var result = TurboJpegImport.TjCompress2(
                    this.compressorHandle,
                    (IntPtr)srcBufPtr,
                    width,
                    stride,
                    height,
                    (int)pixelFormat,
                    ref destBufPtr2,
                    ref destBufSize,
                    (int)subSamp,
                    quality,
                    (int)flags);

                if (result == -1)
                {
                    TJUtils.GetErrorAndThrow();
                }
            }

            return(destBuf.Slice(0, (int)destBufSize));
        }
Exemple #27
0
        /// <summary>
        /// Compresses input image to the jpeg format with specified quality.
        /// </summary>
        /// <param name="srcBuf">
        /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
        /// This buffer is not modified.
        /// </param>
        /// <param name="destBuf">
        /// A <see cref="byte"/> array containing the compressed image.
        /// </param>
        /// <param name="stride">
        /// Bytes per line in the source image.
        /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
        /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
        /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
        /// You can also be clever and use this parameter to skip lines, etc.
        /// Setting this parameter to 0 is the equivalent of setting it to
        /// <c>width * BytesPerPixel</c>.
        /// </param>
        /// <param name="width">Width (in pixels) of the source image.</param>
        /// <param name="height">Height (in pixels) of the source image.</param>
        /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
        /// <param name="subSamp">
        /// The level of chrominance subsampling to be used when
        /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
        /// </param>
        /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
        /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
        /// <returns>
        /// A <see cref="Span{T}"/> which is a slice of <paramref name="destBuf"/> which holds the compressed image.
        /// </returns>
        /// <exception cref="TJException">
        /// Throws if compress function failed.
        /// </exception>
        /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
        /// <exception cref="NotSupportedException">
        /// Some parameters' values are incompatible:
        /// <list type="bullet">
        /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
        /// </list>
        /// </exception>
        public static unsafe Span <byte> Compress(this TJCompressor @this, ReadOnlySpan <byte> srcBuf, Span <byte> destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
        {
            _ = @this ?? throw new ArgumentNullException(nameof(@this));
            var tjPixelFormat = TJGdiPlusUtils.ConvertPixelFormat(pixelFormat);

            return(@this.Compress(srcBuf, destBuf, stride, width, height, tjPixelFormat, subSamp, quality, flags));
        }
Exemple #28
0
 /// <summary>
 /// Compresses input image to the jpeg format with specified quality.
 /// </summary>
 /// <param name="srcBuf">
 /// Image buffer containing RGB, grayscale, or CMYK pixels to be compressed.
 /// This buffer is not modified.
 /// </param>
 /// <param name="destBuf">
 /// A <see cref="byte"/> array containing the compressed image.
 /// </param>
 /// <param name="stride">
 /// Bytes per line in the source image.
 /// Normally, this should be <c>width * BytesPerPixel</c> if the image is unpadded,
 /// or <c>TJPAD(width * BytesPerPixel</c> if each line of the image
 /// is padded to the nearest 32-bit boundary, as is the case for Windows bitmaps.
 /// You can also be clever and use this parameter to skip lines, etc.
 /// Setting this parameter to 0 is the equivalent of setting it to
 /// <c>width * BytesPerPixel</c>.
 /// </param>
 /// <param name="width">Width (in pixels) of the source image.</param>
 /// <param name="height">Height (in pixels) of the source image.</param>
 /// <param name="pixelFormat">Pixel format of the source image (see <see cref="PixelFormat"/> "Pixel formats").</param>
 /// <param name="subSamp">
 /// The level of chrominance subsampling to be used when
 /// generating the JPEG image (see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
 /// </param>
 /// <param name="quality">The image quality of the generated JPEG image (1 = worst, 100 = best).</param>
 /// <param name="flags">The bitwise OR of one or more of the <see cref="TJFlags"/> "flags".</param>
 /// <returns>
 /// The size of the JPEG image (in bytes).
 /// </returns>
 /// <exception cref="TJException">
 /// Throws if compress function failed.
 /// </exception>
 /// <exception cref="ObjectDisposedException">Object is disposed and can not be used anymore.</exception>
 /// <exception cref="NotSupportedException">
 /// Some parameters' values are incompatible:
 /// <list type="bullet">
 /// <item><description>Subsampling not equals to <see cref="TJSubsamplingOption.Gray"/> and pixel format <see cref="TJPixelFormat.Gray"/></description></item>
 /// </list>
 /// </exception>
 public static unsafe int Compress(this TJCompressor @this, byte[] srcBuf, byte[] destBuf, int stride, int width, int height, PixelFormat pixelFormat, TJSubsamplingOption subSamp, int quality, TJFlags flags)
 {
     _ = @this ?? throw new ArgumentNullException(nameof(@this));
     return(@this.Compress(srcBuf.AsSpan(), destBuf.AsSpan(), stride, width, height, pixelFormat, subSamp, quality, flags).Length);
 }
Exemple #29
0
 /// <summary>
 /// The maximum size of the buffer (in bytes) required to hold a JPEG image with
 /// the given parameters.  The number of bytes returned by this function is
 /// larger than the size of the uncompressed source image.  The reason for this
 /// is that the JPEG format uses 16-bit coefficients, and it is thus possible
 /// for a very high-quality JPEG image with very high-frequency content to
 /// expand rather than compress when converted to the JPEG format.  Such images
 /// represent a very rare corner case, but since there is no way to predict the
 /// size of a JPEG image prior to compression, the corner case has to be handled.
 /// </summary>
 /// <param name="width">Width (in pixels) of the image.</param>
 /// <param name="height">Height (in pixels) of the image.</param>
 /// <param name="subSamp">
 /// The level of chrominance subsampling to be used when
 /// generating the JPEG image(see <see cref="TJSubsamplingOption"/> "Chrominance subsampling options".)
 /// </param>
 /// <returns>
 /// The maximum size of the buffer (in bytes) required to hold the image,
 /// or -1 if the arguments are out of bounds.
 /// </returns>
 public int GetBufferSize(int width, int height, TJSubsamplingOption subSamp)
 {
     return((int)TurboJpegImport.TjBufSize(width, height, (int)subSamp));
 }