Exemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageFrameMetaData"/> class
        /// by making a copy from other metadata.
        /// </summary>
        /// <param name="other">
        /// The other <see cref="ImageFrameMetaData"/> to create this instance from.
        /// </param>
        internal ImageFrameMetaData(ImageFrameMetaData other)
        {
            DebugGuard.NotNull(other, nameof(other));

            this.FrameDelay     = other.FrameDelay;
            this.DisposalMethod = other.DisposalMethod;
        }
Exemplo n.º 2
0
        public UnmanagedBuffer(int lengthInElements, UnmanagedBufferLifetimeGuard lifetimeGuard)
        {
            DebugGuard.NotNull(lifetimeGuard, nameof(lifetimeGuard));

            this.lengthInElements = lengthInElements;
            this.lifetimeGuard    = lifetimeGuard;
        }
Exemplo n.º 3
0
        internal bool TryGetPaddedRowSpan(int y, int padding, out Span <T> paddedSpan)
        {
            DebugGuard.MustBeGreaterThanOrEqualTo(y, 0, nameof(y));
            DebugGuard.MustBeLessThan(y, this.Height, nameof(y));

            int stride = this.Width + padding;

            if (this.cachedMemory.Length > 0)
            {
                paddedSpan = this.cachedMemory.Span.Slice(y * this.Width);
                if (paddedSpan.Length < stride)
                {
                    return(false);
                }

                paddedSpan = paddedSpan.Slice(0, stride);
                return(true);
            }

            Memory <T> memory = this.FastMemoryGroup.GetRemainingSliceOfBuffer(y * (long)this.Width);

            if (memory.Length < stride)
            {
                paddedSpan = default;
                return(false);
            }

            paddedSpan = memory.Span.Slice(0, stride);
            return(true);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TiffCcittCompressor" /> class.
 /// </summary>
 /// <param name="output">The output.</param>
 /// <param name="allocator">The allocator.</param>
 /// <param name="width">The width.</param>
 /// <param name="bitsPerPixel">The bits per pixel.</param>
 protected TiffCcittCompressor(Stream output, MemoryAllocator allocator, int width, int bitsPerPixel)
     : base(output, allocator, width, bitsPerPixel)
 {
     DebugGuard.IsTrue(bitsPerPixel == 1, nameof(bitsPerPixel), "CCITT compression requires one bit per pixel");
     this.bytePosition = 0;
     this.bitPosition  = 0;
 }
Exemplo n.º 5
0
        public static unsafe void Copy <T>(Span <T> source, Span <T> destination, int count)
            where T : struct
        {
            DebugGuard.MustBeLessThanOrEqualTo(count, source.Length, nameof(count));
            DebugGuard.MustBeLessThanOrEqualTo(count, destination.Length, nameof(count));

            ref byte srcRef  = ref Unsafe.As <T, byte>(ref MemoryMarshal.GetReference(source));
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RowInterval"/> struct.
        /// </summary>
        public RowInterval(int min, int max)
        {
            DebugGuard.MustBeLessThan(min, max, nameof(min));

            this.Min = min;
            this.Max = max;
        }
Exemplo n.º 7
0
        public T ParseValue <T>(string value, CultureInfo culture)
        {
            DebugGuard.NotNull(culture, nameof(culture));

            Type type = typeof(T);
            ICommandConverter converter = Array.Find(this.converters, x => x.Type.Equals(type));

            if (converter != null)
            {
                return(((ICommandConverter <T>)converter).ConvertFrom(
                           this,
                           culture,
                           WebUtility.UrlDecode(value),
                           type));
            }

            // This special case allows us to reuse the same converter for infinite enum types
            // if one has not already been configured.
            if (type.IsEnum)
            {
                converter = Array.Find(this.converters, x => x.Type.Equals(typeof(Enum)));
                if (converter != null)
                {
                    return((T)((ICommandConverter <object>)converter).ConvertFrom(
                               this,
                               culture,
                               WebUtility.UrlDecode(value),
                               type));
                }
            }

            // We don't actually return here.
            // The compiler just cannot see our exception.
            ThrowNotSupported(type);
            return(default);
Exemplo n.º 8
0
 public void NotNull_TargetNull_ThrowsException()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         DebugGuard.NotNull((object)null, "myParamName");
     });
 }
Exemplo n.º 9
0
        public virtual void Write(TiffBaseCompressor compressor, int rowsPerStrip)
        {
            DebugGuard.IsTrue(this.BytesPerRow == compressor.BytesPerRow, "bytes per row of the compressor does not match tiff color writer");
            int stripsCount = (this.Image.Height + rowsPerStrip - 1) / rowsPerStrip;

            uint[] stripOffsets    = new uint[stripsCount];
            uint[] stripByteCounts = new uint[stripsCount];

            int stripIndex = 0;

            compressor.Initialize(rowsPerStrip);
            for (int y = 0; y < this.Image.Height; y += rowsPerStrip)
            {
                long offset = compressor.Output.Position;

                int height = Math.Min(rowsPerStrip, this.Image.Height - y);
                this.EncodeStrip(y, height, compressor);

                long endOffset = compressor.Output.Position;
                stripOffsets[stripIndex]    = (uint)offset;
                stripByteCounts[stripIndex] = (uint)(endOffset - offset);
                stripIndex++;
            }

            DebugGuard.IsTrue(stripIndex == stripsCount, "stripIndex and stripsCount should match");
            this.AddStripTags(rowsPerStrip, stripOffsets, stripByteCounts);
        }
Exemplo n.º 10
0
        public CieLuv Convert(CieXyz input)
        {
            DebugGuard.NotNull(input, nameof(input));

            // Conversion algorithm described here: http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_Luv.html
            float yr  = input.Y / this.LuvWhitePoint.Y;
            float up  = ComputeUp(input);
            float vp  = ComputeVp(input);
            float upr = ComputeUp(this.LuvWhitePoint);
            float vpr = ComputeVp(this.LuvWhitePoint);

            float l = yr > CieConstants.Epsilon ? ((116 * MathF.Pow(yr, 0.3333333F)) - 16F) : (CieConstants.Kappa * yr);

            if (float.IsNaN(l) || l < 0)
            {
                l = 0;
            }

            float u = 13 * l * (up - upr);
            float v = 13 * l * (vp - vpr);

            if (float.IsNaN(u))
            {
                u = 0;
            }

            if (float.IsNaN(v))
            {
                v = 0;
            }

            return(new CieLuv(l, u, v, this.LuvWhitePoint));
        }
Exemplo n.º 11
0
        /// <summary>
        /// TODO: Does not work with multi-buffer groups, should be specific to Resize.
        /// Copy <paramref name="columnCount"/> columns of <paramref name="buffer"/> inplace,
        /// from positions starting at <paramref name="sourceIndex"/> to positions at <paramref name="destIndex"/>.
        /// </summary>
        internal static unsafe void CopyColumns <T>(
            this Buffer2D <T> buffer,
            int sourceIndex,
            int destIndex,
            int columnCount)
            where T : struct
        {
            DebugGuard.NotNull(buffer, nameof(buffer));
            DebugGuard.MustBeGreaterThanOrEqualTo(sourceIndex, 0, nameof(sourceIndex));
            DebugGuard.MustBeGreaterThanOrEqualTo(destIndex, 0, nameof(sourceIndex));
            CheckColumnRegionsDoNotOverlap(buffer, sourceIndex, destIndex, columnCount);

            int  elementSize = Unsafe.SizeOf <T>();
            int  width       = buffer.Width * elementSize;
            int  sOffset     = sourceIndex * elementSize;
            int  dOffset     = destIndex * elementSize;
            long count       = columnCount * elementSize;

            Span <byte> span = MemoryMarshal.AsBytes(buffer.GetSingleMemory().Span);

            fixed(byte *ptr = span)
            {
                byte *basePtr = ptr;

                for (int y = 0; y < buffer.Height; y++)
                {
                    byte *sPtr = basePtr + sOffset;
                    byte *dPtr = basePtr + dOffset;

                    Buffer.MemoryCopy(sPtr, dPtr, count, count);

                    basePtr += width;
                }
            }
        }
Exemplo n.º 12
0
        public HunterLab Convert(CieXyz input)
        {
            DebugGuard.NotNull(input, nameof(input));

            // Conversion algorithm described here: http://en.wikipedia.org/wiki/Lab_color_space#Hunter_Lab
            float x = input.X, y = input.Y, z = input.Z;
            float xn = this.HunterLabWhitePoint.X, yn = this.HunterLabWhitePoint.Y, zn = this.HunterLabWhitePoint.Z;

            float ka = ComputeKa(this.HunterLabWhitePoint);
            float kb = ComputeKb(this.HunterLabWhitePoint);

            float l = 100 * MathF.Sqrt(y / yn);
            float a = ka * (((x / xn) - (y / yn)) / MathF.Sqrt(y / yn));
            float b = kb * (((y / yn) - (z / zn)) / MathF.Sqrt(y / yn));

            if (float.IsNaN(a))
            {
                a = 0;
            }

            if (float.IsNaN(b))
            {
                b = 0;
            }

            return(new HunterLab(l, a, b, this.HunterLabWhitePoint));
        }
Exemplo n.º 13
0
#pragma warning restore SA1600 // ElementsMustBeDocumented

        /// <summary>
        /// Get/Set scalar elements at a given index
        /// </summary>
        /// <param name="idx">The index</param>
        /// <returns>The float value at the specified index</returns>
        public float this[int idx]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                DebugGuard.MustBeBetweenOrEqualTo(idx, 0, Size - 1, nameof(idx));
                ref float selfRef = ref Unsafe.As <Block8x8F, float>(ref this);
Exemplo n.º 14
0
        public Rgb Convert(Hsl input)
        {
            DebugGuard.NotNull(input, nameof(input));

            float rangedH = input.H / 360F;
            float r       = 0;
            float g       = 0;
            float b       = 0;
            float s       = input.S;
            float l       = input.L;

            if (MathF.Abs(l) > Constants.Epsilon)
            {
                if (MathF.Abs(s) < Constants.Epsilon)
                {
                    r = g = b = l;
                }
                else
                {
                    float temp2 = (l < .5F) ? l * (1F + s) : l + s - (l * s);
                    float temp1 = (2F * l) - temp2;

                    r = GetColorComponent(temp1, temp2, rangedH + 0.3333333F);
                    g = GetColorComponent(temp1, temp2, rangedH);
                    b = GetColorComponent(temp1, temp2, rangedH - 0.3333333F);
                }
            }

            return(new Rgb(r, g, b));
        }
Exemplo n.º 15
0
 public BasicArrayBuffer(T[] array, int length, TestMemoryAllocator allocator)
 {
     this.allocator = allocator;
     DebugGuard.MustBeLessThanOrEqualTo(length, array.Length, nameof(length));
     this.Array  = array;
     this.Length = length;
 }
Exemplo n.º 16
0
        public static unsafe void Copy <T>(Span <T> source, Span <T> destination, int count)
            where T : struct
        {
            DebugGuard.MustBeLessThanOrEqualTo(count, source.Length, nameof(count));
            DebugGuard.MustBeLessThanOrEqualTo(count, destination.Length, nameof(count));

            ref byte srcRef  = ref Unsafe.As <T, byte>(ref source.DangerousGetPinnableReference());
Exemplo n.º 17
0
        /// <summary>
        /// Applies the opactiy weighting for each pixel in a scanline to the target based on the pattern contained in the brush.
        /// </summary>
        /// <param name="scanlineBuffer">The a collection of opacity values between 0 and 1 to be merged with the brushed color value before being applied to the target.</param>
        /// <param name="scanlineWidth">The number of pixels effected by this scanline.</param>
        /// <param name="offset">The offset fromthe begining of <paramref name="scanlineBuffer" /> the opacity data starts.</param>
        /// <param name="x">The x position in the target pixel space that the start of the scanline data corresponds to.</param>
        /// <param name="y">The y position in  the target pixel space that whole scanline corresponds to.</param>
        /// <remarks>scanlineBuffer will be > scanlineWidth but provide and offset in case we want to share a larger buffer across runs.</remarks>
        internal virtual void Apply(float[] scanlineBuffer, int scanlineWidth, int offset, int x, int y)
        {
            DebugGuard.MustBeGreaterThanOrEqualTo(scanlineBuffer.Length, offset + scanlineWidth, nameof(scanlineWidth));

            using (Buffer <float> buffer = new Buffer <float>(scanlineBuffer))
            {
                BufferSpan <float> slice = buffer.Slice(offset);

                for (int xPos = 0; xPos < scanlineWidth; xPos++)
                {
                    int targetX = xPos + x;
                    int targetY = y;

                    float opacity = slice[xPos];
                    if (opacity > Constants.Epsilon)
                    {
                        Vector4 backgroundVector = this.Target[targetX, targetY].ToVector4();

                        Vector4 sourceVector = this[targetX, targetY].ToVector4();

                        Vector4 finalColor = Vector4BlendTransforms.PremultipliedLerp(backgroundVector, sourceVector, opacity);

                        TPixel packed = default(TPixel);
                        packed.PackFromVector4(finalColor);
                        this.Target[targetX, targetY] = packed;
                    }
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageProperty"/> class
        /// by making a copy from another property.
        /// </summary>
        /// <param name="other">
        /// The other <see cref="ImageProperty"/> to create this instance from.
        /// </param>
        internal ImageProperty(ImageProperty other)
        {
            DebugGuard.NotNull(other, nameof(other));

            this.Name  = other.Name;
            this.Value = other.Value;
        }
Exemplo n.º 19
0
        public TiffPaletteWriter(
            ImageFrame <TPixel> image,
            IQuantizer quantizer,
            MemoryAllocator memoryAllocator,
            Configuration configuration,
            TiffEncoderEntriesCollector entriesCollector,
            int bitsPerPixel)
            : base(image, memoryAllocator, configuration, entriesCollector)
        {
            DebugGuard.NotNull(quantizer, nameof(quantizer));
            DebugGuard.NotNull(configuration, nameof(configuration));
            DebugGuard.NotNull(entriesCollector, nameof(entriesCollector));
            DebugGuard.MustBeBetweenOrEqualTo(bitsPerPixel, 4, 8, nameof(bitsPerPixel));

            this.BitsPerPixel      = bitsPerPixel;
            this.maxColors         = this.BitsPerPixel == 4 ? 16 : 256;
            this.colorPaletteSize  = this.maxColors * 3;
            this.colorPaletteBytes = this.colorPaletteSize * 2;
            using IQuantizer <TPixel> frameQuantizer = quantizer.CreatePixelSpecificQuantizer <TPixel>(this.Configuration, new QuantizerOptions()
            {
                MaxColors = this.maxColors
            });
            this.quantizedImage = frameQuantizer.BuildPaletteAndQuantizeFrame(image, image.Bounds());

            this.AddColorMapTag();
        }
        public static TiffBasePlanarColorDecoder <TPixel> CreatePlanar(
            TiffColorType colorType,
            TiffBitsPerSample bitsPerSample,
            ushort[] colorMap,
            Rational[] referenceBlackAndWhite,
            Rational[] ycbcrCoefficients,
            ushort[] ycbcrSubSampling,
            ByteOrder byteOrder)
        {
            switch (colorType)
            {
            case TiffColorType.Rgb888Planar:
                DebugGuard.IsTrue(colorMap == null, "colorMap");
                return(new RgbPlanarTiffColor <TPixel>(bitsPerSample));

            case TiffColorType.YCbCrPlanar:
                return(new YCbCrPlanarTiffColor <TPixel>(referenceBlackAndWhite, ycbcrCoefficients, ycbcrSubSampling));

            case TiffColorType.Rgb161616Planar:
                DebugGuard.IsTrue(colorMap == null, "colorMap");
                return(new Rgb16PlanarTiffColor <TPixel>(byteOrder == ByteOrder.BigEndian));

            case TiffColorType.Rgb242424Planar:
                DebugGuard.IsTrue(colorMap == null, "colorMap");
                return(new Rgb24PlanarTiffColor <TPixel>(byteOrder == ByteOrder.BigEndian));

            case TiffColorType.Rgb323232Planar:
                DebugGuard.IsTrue(colorMap == null, "colorMap");
                return(new Rgb32PlanarTiffColor <TPixel>(byteOrder == ByteOrder.BigEndian));

            default:
                throw TiffThrowHelper.InvalidColorType(colorType.ToString());
            }
        }
Exemplo n.º 21
0
        public static void InterpolateA(LdrColorA c0, LdrColorA c1, int wa, int waprec, LdrColorA outt)
        {
            DebugGuard.MustBeBetweenOrEqualTo(waprec, 2, 4, nameof(waprec));

            int[] aWeights;
            switch (waprec)
            {
            case 2:
            {
                aWeights = Constants.Weights2;
                Debug.Assert(wa < 4, "wc is expected to be smaller then 4");
                break;
            }

            case 3:
            {
                aWeights = Constants.Weights3;
                Debug.Assert(wa < 8, "wc is expected to be smaller then 8");
                break;
            }

            case 4:
            {
                aWeights = Constants.Weights4;
                Debug.Assert(wa < 16, "wc is expected to be smaller then 16");
                break;
            }

            default:
                outt.A = 0;
                return;
            }

            outt.A = (byte)(((c0.A * (uint)(Constants.BC67_WEIGHT_MAX - aWeights[wa])) + (c1.A * (uint)aWeights[wa]) + Constants.BC67_WEIGHT_ROUND) >> Constants.BC67_WEIGHT_SHIFT);
        }
Exemplo n.º 22
0
        public CieXyz Convert(CieLab input)
        {
            DebugGuard.NotNull(input, nameof(input));

            // Conversion algorithm described here: http://www.brucelindbloom.com/index.html?Eqn_Lab_to_XYZ.html
            float l = input.L, a = input.A, b = input.B;
            float fy = (l + 16) / 116F;
            float fx = (a / 500F) + fy;
            float fz = fy - (b / 200F);

            float fx3 = MathF.Pow(fx, 3F);
            float fz3 = MathF.Pow(fz, 3F);

            float xr = fx3 > CieConstants.Epsilon ? fx3 : ((116F * fx) - 16F) / CieConstants.Kappa;
            float yr = l > CieConstants.Kappa * CieConstants.Epsilon ? MathF.Pow((l + 16F) / 116F, 3F) : l / CieConstants.Kappa;
            float zr = fz3 > CieConstants.Epsilon ? fz3 : ((116F * fz) - 16F) / CieConstants.Kappa;

            float wx = input.WhitePoint.X, wy = input.WhitePoint.Y, wz = input.WhitePoint.Z;

            // Avoids XYZ coordinates out range (restricted by 0 and XYZ reference white)
            xr = xr.Clamp(0, 1F);
            yr = yr.Clamp(0, 1F);
            zr = zr.Clamp(0, 1F);

            float x = xr * wx;
            float y = yr * wy;
            float z = zr * wz;

            return(new CieXyz(x, y, z));
        }
Exemplo n.º 23
0
        private static void RunApplication([NotNull] Container container)
        {
            DebugGuard.NotNull(container, nameof(container));

            try
            {
                using (AsyncScopedLifestyle.BeginScope(container))
                {
                    var app        = container.GetInstance <Application>();
                    var mainWindow = container.GetInstance <MainWindow>();

                    void MainWindowOnClosed(object sender, EventArgs e)
                    {
                        mainWindow.Closed -= MainWindowOnClosed;
                        app.Shutdown(0);
                    }

                    // not sure if this is the way to do this.
                    mainWindow.Closed += MainWindowOnClosed;

                    app.Run(mainWindow);
                }
            }

            // ReSharper disable once RedundantCatchClause
            catch
            {
                // Log the exception and exit
#if DEBUG
                throw;
#endif
            }
        }
Exemplo n.º 24
0
        public DataCapturedArgs([NotNull] string key, [NotNull] string data)
        {
            DebugGuard.NotNullOrWhiteSpace(key, nameof(key));
            DebugGuard.NotNull(data, nameof(data)); // can be empty

            Key  = key;
            Data = data;
        }
        /// <inheritdoc/>
        public CieXyz Convert(LinearRgb input)
        {
            DebugGuard.IsTrue(input.WorkingSpace.Equals(this.SourceWorkingSpace), nameof(input.WorkingSpace), "Input and source working spaces must be equal.");

            Vector3 vector = Vector3.Transform(input.Vector, this.conversionMatrix);

            return(new CieXyz(vector));
        }
Exemplo n.º 26
0
        private static void RegisterPlugins([NotNull] Container container)
        {
            DebugGuard.NotNull(container, nameof(container));

            var pluginAssemblies = PluginFinder.FindPluginAssemblies(Path.Combine(AppDomain.CurrentDomain.BaseDirectory));

            container.RegisterPackages(pluginAssemblies);
        }
Exemplo n.º 27
0
        public void MustBeGreaterThanOrEqualTo_IsLess_ThrowsNoException()
        {
            ArgumentOutOfRangeException exception = Assert.Throws <ArgumentOutOfRangeException>(
                () => DebugGuard.MustBeGreaterThanOrEqualTo(1, 2, "myParamName"));

            Assert.Equal("myParamName", exception.ParamName);
            Assert.Contains($"Value 1 must be greater than or equal to 2.", exception.Message);
        }
Exemplo n.º 28
0
        public void MustBeSizedAtLeast_Array_LengthIsLess_ThrowsException()
        {
            ArgumentException exception = Assert.Throws <ArgumentException>(
                () => DebugGuard.MustBeSizedAtLeast <int>(new int[] { 1, 2 }, 3, "myParamName"));

            Assert.Equal("myParamName", exception.ParamName);
            Assert.Contains($"The size must be at least 3.", exception.Message);
        }
Exemplo n.º 29
0
 protected override void CheckPreconditions()
 {
     DebugGuard.Requires(this.Model.Schema.Title == "Article");
     DebugGuard.Requires(this.OutputType == ViewOutputType.Html);
     DebugGuard.Requires(this.EnableOutputDecoration);
     DebugGuard.Requires(this.EnableOutputValidation);
     DebugGuard.Requires(this.Parent == null);
 }
Exemplo n.º 30
0
        public void MustBeGreaterThan_IsLessOrEqual_ThrowsNoException(int value, int min)
        {
            ArgumentOutOfRangeException exception = Assert.Throws <ArgumentOutOfRangeException>(
                () => DebugGuard.MustBeGreaterThan(value, min, "myParamName"));

            Assert.Equal("myParamName", exception.ParamName);
            Assert.Contains($"Value {value} must be greater than {min}.", exception.Message);
        }